@aomex/cron 3.30.7 → 3.30.8-alpha.62.sha-92b25bb

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.
package/dist/index.js CHANGED
@@ -1,803 +1,715 @@
1
- // src/middleware/crons.middleware.ts
2
- import { compose, middleware as middleware5 } from "@aomex/common";
3
-
4
- // src/middleware/start.middleware.ts
5
- import { middleware, sleep as sleep2 } from "@aomex/common";
6
-
7
- // src/lib/collect-crontab.ts
8
- import { Commander } from "@aomex/console";
9
- import { pathToFiles, getFileValues } from "@aomex/internal-file-import";
10
-
11
- // src/middleware/cron.middleware.ts
12
- import { ConsoleMiddleware } from "@aomex/console";
13
-
14
- // src/lib/constant.ts
15
- var DEFAULT_PORT = 9786;
16
- var CONNECT_REFUSED = "ECONNREFUSED";
17
- var ENV_CRON = "AOMEX_CRON";
18
- var ENV_CRON_SCHEDULE_TIME = "AOMEX_CRON_SCHEDULE_TIME";
19
- var ENV_CRON_EXECUTION_TIME = "AOMEX_CRON_EXECUTION_TIME";
20
- var ENV_CRON_NEXT_SCHEDULE_TIME = "AOMEX_CRON_NEXT_SCHEDULE_TIME";
21
- var TELL_CHILD_STOP = "CRON_CHILD_STOP";
22
- var TELL_PARENT_INIT = "CRON_PARENT_INIT";
23
- var TELL_CHILD_RESOLVE = "CRON_CHILD_RESOLVE";
24
- var TELL_CHILD_REJECT = "CRON_CHILD_REJECT";
25
- var TELL_PARENT_ENDED = "TELL_PARENT_ENDED";
26
-
1
+ import { I18n, compose, createI18n, middleware, sleep } from "@aomex/common";
2
+ import { Commander, ConsoleMiddleware, scriptName, terminal } from "@aomex/console";
3
+ import { getFileValues, pathToFiles } from "@aomex/internal-file-import";
4
+ import { Caching } from "@aomex/cache";
5
+ import { CacheMemoryAdapter } from "@aomex/cache/memory";
6
+ import * as cronParser from "cron-parser";
7
+ import { bytes, sleep as sleep$1 } from "@aomex/internal-tools";
8
+ import { spawn } from "node:child_process";
9
+ import { randomBytes } from "node:crypto";
10
+ import net from "node:net";
11
+ import formatDuration from "format-duration";
12
+ import pidusage from "pidusage";
13
+ const ENV_CRON = "AOMEX_CRON";
14
+ const ENV_CRON_SCHEDULE_TIME = "AOMEX_CRON_SCHEDULE_TIME";
15
+ const ENV_CRON_EXECUTION_TIME = "AOMEX_CRON_EXECUTION_TIME";
16
+ const ENV_CRON_NEXT_SCHEDULE_TIME = "AOMEX_CRON_NEXT_SCHEDULE_TIME";
17
+ const TELL_CHILD_STOP = "CRON_CHILD_STOP";
18
+ const TELL_PARENT_INIT = "CRON_PARENT_INIT";
19
+ const TELL_CHILD_RESOLVE = "CRON_CHILD_RESOLVE";
20
+ const TELL_CHILD_REJECT = "CRON_CHILD_REJECT";
21
+ const TELL_PARENT_ENDED = "TELL_PARENT_ENDED";
27
22
  // src/middleware/cron.middleware.ts
28
23
  var CronMiddleware = class extends ConsoleMiddleware {
29
- constructor(options) {
30
- super(async (ctx, next) => {
31
- if (process.env[ENV_CRON] === "1") {
32
- let alive = true;
33
- const { promise: init, resolve } = Promise.withResolvers();
34
- const onInitOrStop = (message) => {
35
- switch (message) {
36
- case TELL_CHILD_RESOLVE:
37
- alive = true;
38
- resolve(void 0);
39
- break;
40
- case TELL_CHILD_REJECT:
41
- alive = false;
42
- resolve(void 0);
43
- break;
44
- case TELL_CHILD_STOP:
45
- alive = false;
46
- break;
47
- }
48
- };
49
- process.on("message", onInitOrStop);
50
- process.send(TELL_PARENT_INIT);
51
- const nextTime = new Date(process.env[ENV_CRON_NEXT_SCHEDULE_TIME]);
52
- ctx.cron = {
53
- executionTime: new Date(process.env[ENV_CRON_EXECUTION_TIME]),
54
- scheduleTime: new Date(process.env[ENV_CRON_SCHEDULE_TIME]),
55
- nextScheduleTime: nextTime,
56
- isAlive: () => alive,
57
- isCurrentEpoch: () => nextTime.getTime() - Date.now() > 0
58
- };
59
- try {
60
- await init;
61
- await next();
62
- } finally {
63
- process.removeListener("message", onInitOrStop);
64
- process.send(TELL_PARENT_ENDED);
65
- }
66
- } else {
67
- const now = /* @__PURE__ */ new Date();
68
- ctx.cron = {
69
- executionTime: now,
70
- scheduleTime: now,
71
- nextScheduleTime: now,
72
- isAlive: () => true,
73
- isCurrentEpoch: () => true
74
- };
75
- return next();
76
- }
77
- });
78
- this.options = options;
79
- }
24
+ options;
25
+ constructor(options) {
26
+ super(async (ctx, next) => {
27
+ if (process.env["AOMEX_CRON"] === "1") {
28
+ let alive = true;
29
+ const { promise: init, resolve } = Promise.withResolvers();
30
+ const onInitOrStop = (message) => {
31
+ switch (message) {
32
+ case TELL_CHILD_RESOLVE:
33
+ alive = true;
34
+ resolve(void 0);
35
+ break;
36
+ case TELL_CHILD_REJECT:
37
+ alive = false;
38
+ resolve(void 0);
39
+ break;
40
+ case TELL_CHILD_STOP: alive = false;
41
+ }
42
+ };
43
+ process.on("message", onInitOrStop);
44
+ process.send(TELL_PARENT_INIT);
45
+ const nextTime = new Date(process.env[ENV_CRON_NEXT_SCHEDULE_TIME]);
46
+ ctx.cron = {
47
+ executionTime: new Date(process.env[ENV_CRON_EXECUTION_TIME]),
48
+ scheduleTime: new Date(process.env[ENV_CRON_SCHEDULE_TIME]),
49
+ nextScheduleTime: nextTime,
50
+ isAlive: () => alive,
51
+ isCurrentEpoch: () => nextTime.getTime() - Date.now() > 0
52
+ };
53
+ try {
54
+ await init;
55
+ await next();
56
+ } finally {
57
+ process.removeListener("message", onInitOrStop);
58
+ process.send(TELL_PARENT_ENDED);
59
+ }
60
+ } else {
61
+ const now = /* @__PURE__ */ new Date();
62
+ ctx.cron = {
63
+ executionTime: now,
64
+ scheduleTime: now,
65
+ nextScheduleTime: now,
66
+ isAlive: () => true,
67
+ isCurrentEpoch: () => true
68
+ };
69
+ return next();
70
+ }
71
+ });
72
+ this.options = options;
73
+ }
80
74
  };
81
- var cron = (options) => {
82
- return new CronMiddleware(typeof options === "string" ? { time: options } : options);
75
+ /**
76
+ * 收集定时任务
77
+ *
78
+ * 如果传递字符串,则为cron时间表达式(支持秒)。如:`1-10,20 * * * *`
79
+ */
80
+ const cron = (options) => {
81
+ return new CronMiddleware(typeof options === "string" ? { time: options } : options);
83
82
  };
84
-
85
- // src/lib/cron.ts
86
- import { scriptName } from "@aomex/console";
87
- import { CacheMemoryAdapter, Caching } from "@aomex/cache";
88
- import * as cronParser from "cron-parser";
89
-
90
83
  // src/lib/task.ts
91
- import { sleep } from "@aomex/internal-tools";
92
- import { spawn } from "child_process";
93
- import { randomBytes } from "crypto";
94
84
  var Task = class {
95
- constructor(cron2, currentTimestamp, nextTimestamp) {
96
- this.cron = cron2;
97
- this.currentTimestamp = currentTimestamp;
98
- this.nextTimestamp = nextTimestamp;
99
- this.concurrentKey = `aomex-cron|v:${cron2.argv}|t:${cron2.time}|s:1|c:${cron2.concurrent}`;
100
- this.filePath = process.argv[1];
101
- this.execArgv = [...process.execArgv];
102
- if (!this.execArgv.includes("--enable-source-maps")) {
103
- this.execArgv.unshift("--enable-source-maps");
104
- }
105
- }
106
- child = null;
107
- concurrentKey;
108
- filePath;
109
- execArgv;
110
- /**
111
- * 并发锁定时间。非正常退出时要等20分钟才释放,正常情况下任务执行完就会立即释放。
112
- * 之所以要设置这么长,是为了防止服务器卡顿时,容易造成任务双跑问题
113
- */
114
- concurrentExpireDuration = 12e5;
115
- get pid() {
116
- return this.child?.pid?.toString();
117
- }
118
- async consume() {
119
- const result = await this.win();
120
- if (result === "lose") return;
121
- const pong = this.ping(result.slot, result.token);
122
- try {
123
- await this.runChildProcess();
124
- } finally {
125
- await pong();
126
- }
127
- }
128
- async runChildProcess() {
129
- if (this.child) return;
130
- const { argv } = this.cron;
131
- const { promise, resolve } = Promise.withResolvers();
132
- const childProcess = spawn(
133
- process.argv0,
134
- [...this.execArgv, this.filePath, ...argv],
135
- {
136
- cwd: process.cwd(),
137
- env: {
138
- /**
139
- * 支持颜色输出。默认值是 `0` 代表不输出颜色。
140
- * @link https://nodejs.org/api/tty.html#writestreamgetcolordepthenv
141
- */
142
- FORCE_COLOR: "3",
143
- ...process.env,
144
- [ENV_CRON]: "1",
145
- [ENV_CRON_SCHEDULE_TIME]: new Date(this.currentTimestamp).toISOString(),
146
- [ENV_CRON_EXECUTION_TIME]: (/* @__PURE__ */ new Date()).toISOString(),
147
- [ENV_CRON_NEXT_SCHEDULE_TIME]: new Date(this.nextTimestamp).toISOString()
148
- },
149
- stdio: ["inherit", "inherit", "inherit", "ipc"]
150
- }
151
- );
152
- this.child = childProcess;
153
- childProcess.on("close", resolve);
154
- childProcess.on("exit", resolve);
155
- childProcess.on("error", resolve);
156
- let timer = null;
157
- childProcess.on("message", (message) => {
158
- if (message === TELL_PARENT_INIT) {
159
- childProcess.send(this.cron.stopping ? TELL_CHILD_REJECT : TELL_CHILD_RESOLVE);
160
- }
161
- if (message === TELL_PARENT_ENDED) {
162
- timer = setTimeout(() => {
163
- try {
164
- childProcess.kill();
165
- } finally {
166
- resolve(void 0);
167
- timer = null;
168
- }
169
- }, 3e4);
170
- }
171
- });
172
- await promise.finally(() => {
173
- this.child = null;
174
- if (timer) {
175
- clearTimeout(timer);
176
- }
177
- });
178
- }
179
- getWaitingTimeout() {
180
- return this.cron.getWaitingTimeout(this.nextTimestamp - this.currentTimestamp);
181
- }
182
- async win() {
183
- const { cache, globalRunningLevel, globalWinnerLevel } = this.cron;
184
- const waitingTimeout = this.getWaitingTimeout();
185
- const startTime = Date.now();
186
- const token = `${process.pid}:${Date.now()}:${randomBytes(16).toString("hex")}`;
187
- const maxConcurrent = Math.min(this.cron.concurrent, 65535);
188
- const waitingLevel = Math.max(0, globalRunningLevel - globalWinnerLevel);
189
- await sleep(globalWinnerLevel * 50);
190
- await sleep(waitingLevel * 5);
191
- while (true) {
192
- for (let i = 0; i < maxConcurrent; ++i) {
193
- if (this.cron.stopping) return "lose";
194
- const slot = `${this.concurrentKey}|slot:${i}`;
195
- const win = await cache.setNX(slot, token, this.concurrentExpireDuration);
196
- if (win) return { slot, token };
197
- await sleep(5);
198
- }
199
- if (waitingTimeout <= 0) return "lose";
200
- if (startTime + waitingTimeout <= Date.now()) return "lose";
201
- await sleep(500);
202
- continue;
203
- }
204
- }
205
- ping(slot, token) {
206
- const cache = this.cron.cache;
207
- const CHECK_INTERVAL = 15e3;
208
- let isStopped = false;
209
- const checkTask = async () => {
210
- let shouldContinue = true;
211
- if (isStopped) return;
212
- try {
213
- const remoteToken = await cache.get(slot);
214
- if (remoteToken === token) {
215
- await cache.expire(slot, this.concurrentExpireDuration);
216
- return;
217
- }
218
- if (isStopped) return;
219
- if (remoteToken === null) {
220
- const win = await cache.setNX(slot, token, this.concurrentExpireDuration);
221
- if (win) return;
222
- }
223
- try {
224
- this.child?.send(TELL_CHILD_STOP);
225
- } catch {
226
- }
227
- await sleep(5e3);
228
- this.child?.kill();
229
- shouldContinue = false;
230
- } finally {
231
- if (shouldContinue && !isStopped) {
232
- timer = setTimeout(checkTask, CHECK_INTERVAL);
233
- }
234
- }
235
- };
236
- let timer = setTimeout(checkTask, CHECK_INTERVAL);
237
- const mustAfterWaitingTimeout = new Promise((resolve) => {
238
- sleep(this.getWaitingTimeout() + 1e3).then(resolve);
239
- });
240
- return async () => {
241
- isStopped = true;
242
- clearTimeout(timer);
243
- await mustAfterWaitingTimeout;
244
- const remoteToken = await cache.get(slot);
245
- if (remoteToken === token) {
246
- await cache.delete(slot);
247
- }
248
- };
249
- }
85
+ cron;
86
+ currentTimestamp;
87
+ nextTimestamp;
88
+ child = null;
89
+ concurrentKey;
90
+ filePath;
91
+ execArgv;
92
+ /**
93
+ * 并发锁定时间。非正常退出时要等20分钟才释放,正常情况下任务执行完就会立即释放。
94
+ * 之所以要设置这么长,是为了防止服务器卡顿时,容易造成任务双跑问题
95
+ */
96
+ concurrentExpireDuration = 12e5;
97
+ constructor(cron, currentTimestamp, nextTimestamp) {
98
+ this.cron = cron;
99
+ this.currentTimestamp = currentTimestamp;
100
+ this.nextTimestamp = nextTimestamp;
101
+ this.concurrentKey = `aomex-cron|v:${cron.argv}|t:${cron.time}|s:1|c:${cron.concurrent}`;
102
+ this.filePath = process.argv[1];
103
+ this.execArgv = [...process.execArgv];
104
+ if (!this.execArgv.includes("--enable-source-maps")) this.execArgv.unshift("--enable-source-maps");
105
+ }
106
+ get pid() {
107
+ return this.child?.pid?.toString();
108
+ }
109
+ async consume() {
110
+ const result = await this.win();
111
+ if (result === "lose") return;
112
+ const pong = this.ping(result.slot, result.token);
113
+ try {
114
+ await this.runChildProcess();
115
+ } finally {
116
+ await pong();
117
+ }
118
+ }
119
+ async runChildProcess() {
120
+ if (this.child) return;
121
+ const { argv } = this.cron;
122
+ const { promise, resolve } = Promise.withResolvers();
123
+ const childProcess = spawn(process.argv0, [
124
+ ...this.execArgv,
125
+ this.filePath,
126
+ ...argv
127
+ ], {
128
+ cwd: process.cwd(),
129
+ env: {
130
+ /**
131
+ * 支持颜色输出。默认值是 `0` 代表不输出颜色。
132
+ * @link https://nodejs.org/api/tty.html#writestreamgetcolordepthenv
133
+ */
134
+ FORCE_COLOR: "3",
135
+ ...process.env,
136
+ [ENV_CRON]: "1",
137
+ [ENV_CRON_SCHEDULE_TIME]: new Date(this.currentTimestamp).toISOString(),
138
+ [ENV_CRON_EXECUTION_TIME]: (/* @__PURE__ */ new Date()).toISOString(),
139
+ [ENV_CRON_NEXT_SCHEDULE_TIME]: new Date(this.nextTimestamp).toISOString()
140
+ },
141
+ stdio: [
142
+ "inherit",
143
+ "inherit",
144
+ "inherit",
145
+ "ipc"
146
+ ]
147
+ });
148
+ this.child = childProcess;
149
+ childProcess.on("close", resolve);
150
+ childProcess.on("exit", resolve);
151
+ childProcess.on("error", resolve);
152
+ let timer = null;
153
+ childProcess.on("message", (message) => {
154
+ if (message === "CRON_PARENT_INIT") childProcess.send(this.cron.stopping ? TELL_CHILD_REJECT : TELL_CHILD_RESOLVE);
155
+ if (message === "TELL_PARENT_ENDED") timer = setTimeout(() => {
156
+ try {
157
+ childProcess.kill();
158
+ } finally {
159
+ resolve(void 0);
160
+ timer = null;
161
+ }
162
+ }, 3e4);
163
+ });
164
+ await promise.finally(() => {
165
+ this.child = null;
166
+ if (timer) clearTimeout(timer);
167
+ });
168
+ }
169
+ getWaitingTimeout() {
170
+ return this.cron.getWaitingTimeout(this.nextTimestamp - this.currentTimestamp);
171
+ }
172
+ async win() {
173
+ const { cache, globalRunningLevel, globalWinnerLevel } = this.cron;
174
+ const waitingTimeout = this.getWaitingTimeout();
175
+ const startTime = Date.now();
176
+ const token = `${process.pid}:${Date.now()}:${randomBytes(16).toString("hex")}`;
177
+ const maxConcurrent = Math.min(this.cron.concurrent, 65535);
178
+ const waitingLevel = Math.max(0, globalRunningLevel - globalWinnerLevel);
179
+ await sleep$1(globalWinnerLevel * 20);
180
+ await sleep$1(waitingLevel * 5);
181
+ while (true) {
182
+ for (let i = 0; i < maxConcurrent; ++i) {
183
+ if (this.cron.stopping) return "lose";
184
+ const slot = `${this.concurrentKey}|slot:${i}`;
185
+ if (await cache.setNX(slot, token, this.concurrentExpireDuration)) return {
186
+ slot,
187
+ token
188
+ };
189
+ await sleep$1(5);
190
+ }
191
+ if (waitingTimeout <= 0) return "lose";
192
+ if (startTime + waitingTimeout <= Date.now()) return "lose";
193
+ await sleep$1(500);
194
+ }
195
+ }
196
+ ping(slot, token) {
197
+ const cache = this.cron.cache;
198
+ const CHECK_INTERVAL = 15e3;
199
+ let isStopped = false;
200
+ const checkTask = async () => {
201
+ let shouldContinue = true;
202
+ if (isStopped) return;
203
+ try {
204
+ const remoteToken = await cache.get(slot);
205
+ if (remoteToken === token) {
206
+ await cache.expire(slot, this.concurrentExpireDuration);
207
+ return;
208
+ }
209
+ if (isStopped) return;
210
+ if (remoteToken === null) {
211
+ if (await cache.setNX(slot, token, this.concurrentExpireDuration)) return;
212
+ }
213
+ try {
214
+ this.child?.send(TELL_CHILD_STOP);
215
+ } catch {}
216
+ await sleep$1(5e3);
217
+ this.child?.kill();
218
+ shouldContinue = false;
219
+ } finally {
220
+ if (shouldContinue && !isStopped) timer = setTimeout(checkTask, CHECK_INTERVAL);
221
+ }
222
+ };
223
+ let timer = setTimeout(checkTask, CHECK_INTERVAL);
224
+ const mustAfterWaitingTimeout = new Promise((resolve) => {
225
+ sleep$1(this.getWaitingTimeout() + 5e3).then(resolve);
226
+ });
227
+ return async () => {
228
+ isStopped = true;
229
+ clearTimeout(timer);
230
+ await mustAfterWaitingTimeout;
231
+ if (await cache.get(slot) === token) await cache.delete(slot);
232
+ };
233
+ }
250
234
  };
251
-
252
- // src/i18n/index.ts
253
- import { I18n as I18n3 } from "@aomex/common";
254
-
255
235
  // src/i18n/locales/zh-cn.ts
256
- import { I18n } from "@aomex/common";
257
- var zh = I18n.define({
258
- eject: "\u5BFC\u51FA\u5B9A\u65F6\u4EFB\u52A1\u5217\u8868",
259
- start: "\u542F\u52A8\u5B9A\u65F6\u4EFB\u52A1",
260
- stop: "\u9000\u51FA\u5B9A\u65F6\u4EFB\u52A1",
261
- stats: "\u67E5\u770B\u5B9A\u65F6\u4EFB\u52A1\u6267\u884C\u72B6\u6001",
262
- not_started: "\u5B9A\u65F6\u4EFB\u52A1\u672A\u542F\u52A8\uFF0C\u7AEF\u53E3\uFF1A{{port}}",
263
- invalid_cron_time: "\u65F6\u95F4\u8868\u8FBE\u5F0F\u4E0D\u5408\u6CD5\uFF1A{{time}}"
236
+ const zh = I18n.define({
237
+ eject: "导出定时任务列表",
238
+ start: "启动定时任务",
239
+ stop: "停止定时任务",
240
+ stats: "查看定时任务执行状态",
241
+ not_started: "定时任务未启动,端口:{{port}}",
242
+ invalid_cron_time: "无效的 Cron 表达式:{{time}}",
243
+ invalid_port: "无效的服务端口:{{port}}(有效范围:1-65535)"
264
244
  });
265
-
266
245
  // src/i18n/locales/en-us.ts
267
- import { I18n as I18n2 } from "@aomex/common";
268
- var en = I18n2.satisfies(zh).define({
269
- eject: "Eject cron tasks to crontab",
270
- start: "Start cron tasks",
271
- stop: "Stop cron tasks",
272
- stats: "Show cron tasks stats",
273
- not_started: "cron not started with port: {{port}}",
274
- invalid_cron_time: "Invalid cron time expression: {{time}}"
246
+ const en = I18n.satisfies(zh).define({
247
+ eject: "Eject cron tasks to crontab",
248
+ start: "Start cron tasks",
249
+ stop: "Stop scheduled tasks",
250
+ stats: "Show cron tasks stats",
251
+ not_started: "cron not started with port: {{port}}",
252
+ invalid_cron_time: "Invalid cron expression: {{time}}",
253
+ invalid_port: "Invalid server port: {{port}} (valid range: 1-65535)"
275
254
  });
276
-
277
- // src/i18n/locales/index.ts
278
- var locales = {
279
- zh_CN: zh,
280
- en_US: en
281
- };
282
-
283
255
  // src/i18n/index.ts
284
- var i18n = new I18n3({
285
- resources: locales,
286
- defaultLanguage: "zh_CN"
256
+ const i18n = createI18n({
257
+ zh,
258
+ en,
259
+ load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
287
260
  });
288
-
289
261
  // src/lib/cron.ts
290
262
  var Cron = class {
291
- constructor(options) {
292
- this.options = options;
293
- this._globalCrontab = options.crontab;
294
- const scheduleTime = "time" in options ? options.time : [
295
- options.second ?? "0",
296
- options.minute ?? "*",
297
- options.hour ?? "*",
298
- options.dayOfMonth ?? "*",
299
- options.month ?? "*",
300
- options.dayOfWeek ?? "*"
301
- ].join(" ");
302
- try {
303
- this.cronExpression = cronParser.CronExpressionParser.parse(scheduleTime);
304
- this.cronExpressionForNext = cronParser.CronExpressionParser.parse(scheduleTime);
305
- } catch {
306
- throw new Error(i18n.t("invalid_cron_time", { time: scheduleTime }));
307
- }
308
- this.time = this.cronExpression.stringify(true);
309
- this.cronExpressionForNext.next();
310
- }
311
- cronExpression;
312
- cronExpressionForNext;
313
- stopping = false;
314
- handle = null;
315
- runningLevel = 0;
316
- time;
317
- _time;
318
- _seconds;
319
- _argv;
320
- _cache;
321
- _tasks = /* @__PURE__ */ new Set();
322
- _globalCrontab;
323
- get command() {
324
- return this.options.command;
325
- }
326
- get globalWinnerLevel() {
327
- let level = 0;
328
- for (const cron2 of this._globalCrontab) {
329
- level += cron2.getPIDs().length;
330
- }
331
- return level;
332
- }
333
- get globalRunningLevel() {
334
- let level = 0;
335
- for (const cron2 of this._globalCrontab) {
336
- level += cron2.runningLevel;
337
- }
338
- return level;
339
- }
340
- get concurrent() {
341
- let { concurrent = 1 } = this.options;
342
- if (concurrent === "infinity") concurrent = Infinity;
343
- return Math.max(1, concurrent);
344
- }
345
- getWaitingTimeout(timeDelta = Infinity) {
346
- return Math.max(
347
- 0,
348
- Math.min(this.options.waitingTimeout ?? 1e4, Math.abs(timeDelta))
349
- );
350
- }
351
- get cache() {
352
- return this._cache ??= this.options.cache || new Caching(new CacheMemoryAdapter());
353
- }
354
- get argv() {
355
- return this._argv ??= [this.options.command, ...this.options.args || []].map(
356
- String
357
- );
358
- }
359
- getPIDs() {
360
- return [...this._tasks].map((task) => task.pid).filter((pid) => pid !== void 0);
361
- }
362
- async start() {
363
- if (!this.cronExpression.hasNext()) return;
364
- const currentTime = this.cronExpression.next().getTime();
365
- const nextTime = this.cronExpressionForNext.next().getTime();
366
- while (true) {
367
- const delta = Math.min(9e5, currentTime - Date.now());
368
- await this.delay(delta);
369
- if (this.stopping) return;
370
- if (currentTime - Date.now() <= 0) {
371
- ++this.runningLevel;
372
- const task = new Task(this, currentTime, nextTime);
373
- this._tasks.add(task);
374
- task.consume().finally(() => {
375
- this._tasks.delete(task);
376
- --this.runningLevel;
377
- });
378
- break;
379
- }
380
- }
381
- return this.start();
382
- }
383
- delay(delta) {
384
- const { promise, resolve } = Promise.withResolvers();
385
- const timer = setTimeout(() => {
386
- this.handle = null;
387
- resolve(void 0);
388
- }, delta);
389
- this.handle = { timer, resolve };
390
- return promise;
391
- }
392
- stop() {
393
- this.stopping = true;
394
- if (this.handle) {
395
- clearTimeout(this.handle.timer);
396
- this.handle.resolve();
397
- }
398
- setTimeout(() => {
399
- this._tasks.forEach((task) => {
400
- task.child?.send(TELL_CHILD_STOP);
401
- });
402
- }, 1e3);
403
- }
404
- toString() {
405
- return [
406
- this.time,
407
- scriptName,
408
- ...this.argv.map((value) => value.includes(" ") ? `"${value}"` : value)
409
- ].join(" ");
410
- }
411
- toJSON() {
412
- return {
413
- command: this.command,
414
- time: this.time,
415
- argv: this.argv,
416
- concurrent: this.concurrent,
417
- waitingTimeout: this.getWaitingTimeout()
418
- };
419
- }
263
+ options;
264
+ cronExpression;
265
+ cronExpressionForNext;
266
+ stopping = false;
267
+ handle = null;
268
+ runningLevel = 0;
269
+ time;
270
+ _time;
271
+ _seconds;
272
+ _argv;
273
+ _cache;
274
+ _tasks = /* @__PURE__ */ new Set();
275
+ _globalCrontab;
276
+ constructor(options) {
277
+ this.options = options;
278
+ this._globalCrontab = options.crontab;
279
+ const scheduleTime = "time" in options ? options.time : [
280
+ options.second ?? "0",
281
+ options.minute ?? "*",
282
+ options.hour ?? "*",
283
+ options.dayOfMonth ?? "*",
284
+ options.month ?? "*",
285
+ options.dayOfWeek ?? "*"
286
+ ].join(" ");
287
+ if ("time" in options) {
288
+ const fieldCount = scheduleTime.trim().split(/\s+/).filter(Boolean).length;
289
+ if (fieldCount < 5 || fieldCount > 6) throw new Error(i18n.t("invalid_cron_time", { time: scheduleTime }));
290
+ }
291
+ try {
292
+ this.cronExpression = cronParser.CronExpressionParser.parse(scheduleTime);
293
+ this.cronExpressionForNext = cronParser.CronExpressionParser.parse(scheduleTime);
294
+ } catch {
295
+ throw new Error(i18n.t("invalid_cron_time", { time: scheduleTime }));
296
+ }
297
+ this.time = this.cronExpression.stringify(true);
298
+ this.cronExpressionForNext.next();
299
+ }
300
+ get command() {
301
+ return this.options.command;
302
+ }
303
+ get globalWinnerLevel() {
304
+ let level = 0;
305
+ for (const cron of this._globalCrontab) level += cron.getPIDs().length;
306
+ return level;
307
+ }
308
+ get globalRunningLevel() {
309
+ let level = 0;
310
+ for (const cron of this._globalCrontab) level += cron.runningLevel;
311
+ return level;
312
+ }
313
+ get concurrent() {
314
+ let { concurrent = 1 } = this.options;
315
+ if (concurrent === "infinity") concurrent = Infinity;
316
+ return Math.max(1, concurrent);
317
+ }
318
+ getWaitingTimeout(timeDelta = Infinity) {
319
+ return Math.max(0, Math.min(this.options.waitingTimeout ?? 1e4, Math.abs(timeDelta)));
320
+ }
321
+ get cache() {
322
+ return this._cache ??= new Caching(this.options.store ?? new CacheMemoryAdapter());
323
+ }
324
+ get argv() {
325
+ return this._argv ??= [this.options.command, ...this.options.args || []].map(String);
326
+ }
327
+ getPIDs() {
328
+ return [...this._tasks].map((task) => task.pid).filter((pid) => pid !== void 0);
329
+ }
330
+ async start() {
331
+ if (!this.cronExpression.hasNext()) return;
332
+ const currentTime = this.cronExpression.next().getTime();
333
+ const nextTime = this.cronExpressionForNext.next().getTime();
334
+ while (true) {
335
+ /**
336
+ * setTimeout的最大延时值是 `2^31-1`(约为24.85天) ,超过这个值会被立即执行。
337
+ * 拆分延时值可让执行时机更精确。
338
+ */
339
+ const delta = Math.min(9e5, currentTime - Date.now());
340
+ await this.delay(delta);
341
+ if (this.stopping) return;
342
+ if (currentTime - Date.now() <= 0) {
343
+ ++this.runningLevel;
344
+ const task = new Task(this, currentTime, nextTime);
345
+ this._tasks.add(task);
346
+ task.consume().finally(() => {
347
+ this._tasks.delete(task);
348
+ --this.runningLevel;
349
+ });
350
+ break;
351
+ }
352
+ }
353
+ return this.start();
354
+ }
355
+ delay(delta) {
356
+ const { promise, resolve } = Promise.withResolvers();
357
+ const timer = setTimeout(() => {
358
+ this.handle = null;
359
+ resolve(void 0);
360
+ }, delta);
361
+ this.handle = {
362
+ timer,
363
+ resolve
364
+ };
365
+ return promise;
366
+ }
367
+ stop() {
368
+ this.stopping = true;
369
+ if (this.handle) {
370
+ clearTimeout(this.handle.timer);
371
+ this.handle.resolve();
372
+ }
373
+ setTimeout(() => {
374
+ this._tasks.forEach((task) => {
375
+ task.child?.send(TELL_CHILD_STOP);
376
+ });
377
+ }, 1e3);
378
+ }
379
+ toString() {
380
+ return [
381
+ this.time,
382
+ scriptName,
383
+ ...this.argv.map((value) => value.includes(" ") ? `"${value}"` : value)
384
+ ].join(" ");
385
+ }
386
+ toJSON() {
387
+ return {
388
+ command: this.command,
389
+ time: this.time,
390
+ argv: this.argv,
391
+ concurrent: this.concurrent,
392
+ waitingTimeout: this.getWaitingTimeout()
393
+ };
394
+ }
420
395
  };
421
-
422
396
  // src/lib/collect-crontab.ts
423
- var collectCrontab = async (opts) => {
424
- const files = await pathToFiles(opts.commanders);
425
- const commanders = await getFileValues(
426
- files,
427
- (item) => !!item && item instanceof Commander
428
- );
429
- const crontab = [];
430
- for (const commander of commanders) {
431
- for (const builder of commander["builders"]) {
432
- for (const middleware6 of builder["middlewareList"]) {
433
- if (middleware6 instanceof CronMiddleware) {
434
- crontab.push(
435
- new Cron({
436
- ...opts,
437
- ...middleware6["options"],
438
- command: builder.commands[0],
439
- crontab
440
- })
441
- );
442
- }
443
- }
444
- }
445
- }
446
- return crontab;
397
+ const collectCrontab = async (opts) => {
398
+ const files = await pathToFiles(opts.commanders);
399
+ const commanders = await getFileValues(files, (item) => !!item && item instanceof Commander);
400
+ const crontab = [];
401
+ for (const commander of commanders) for (const builder of commander["builders"]) for (const middleware of builder["middlewareList"]) if (middleware instanceof CronMiddleware) crontab.push(new Cron({
402
+ ...opts,
403
+ ...middleware["options"],
404
+ command: builder.commands[0],
405
+ crontab
406
+ }));
407
+ return crontab;
447
408
  };
448
-
449
409
  // src/middleware/start.middleware.ts
450
- import net from "net";
451
- var commandName = "cron:start";
452
- var start = (opts) => {
453
- return middleware.console({
454
- fn: async (ctx, next) => {
455
- if (ctx.input.command !== commandName) return next();
456
- ctx.commandMatched = true;
457
- const crontab = await collectCrontab(opts);
458
- const DELAY = 300;
459
- if (!crontab.length) return;
460
- const stopTasks = async (callback) => {
461
- crontab.forEach((cron2) => cron2.stop());
462
- let remain = crontab.length;
463
- await Promise.all(
464
- crontab.map((cron2) => {
465
- const { promise, resolve } = Promise.withResolvers();
466
- const timer = setInterval(() => {
467
- if (!cron2.runningLevel) {
468
- clearInterval(timer);
469
- resolve(void 0);
470
- callback?.(--remain);
471
- }
472
- }, DELAY);
473
- return promise;
474
- })
475
- );
476
- };
477
- const collectRunners = () => {
478
- return crontab.reduce(
479
- (carry, cron2) => carry.concat(
480
- cron2.getPIDs().map((pid) => ({
481
- pid,
482
- command: cron2.argv.join(" "),
483
- schedule: cron2.time
484
- }))
485
- ),
486
- []
487
- );
488
- };
489
- const sendStopMessages = async (socket) => {
490
- socket.write(
491
- JSON.stringify({ runners: collectRunners() }) + "\n"
492
- );
493
- await stopTasks(() => {
494
- socket.write(
495
- JSON.stringify({
496
- runningPIDs: crontab.flatMap((cron2) => cron2.getPIDs())
497
- }) + "\n"
498
- );
499
- });
500
- socket.destroy();
501
- };
502
- const sendStatsMessage = (socket) => {
503
- socket.write(
504
- JSON.stringify({ runners: collectRunners() }) + "\n"
505
- );
506
- };
507
- const server = net.createServer(async (socket) => {
508
- socket.on("data", async (data) => {
509
- switch (data.toString()) {
510
- case "cron:stop":
511
- await sendStopMessages(socket);
512
- break;
513
- case "cron:stats":
514
- sendStatsMessage(socket);
515
- break;
516
- }
517
- });
518
- socket.on("error", (err) => {
519
- console.log(`[cron:start] ${err instanceof Error ? err.message : String(err)}`);
520
- });
521
- });
522
- const PORT = opts.port || DEFAULT_PORT;
523
- server.listen(PORT);
524
- process.once("SIGINT", async () => {
525
- stopTasks();
526
- });
527
- await Promise.all(crontab.map((cron2) => cron2.start()));
528
- await stopTasks();
529
- await sleep2(DELAY + 10);
530
- server.close();
531
- },
532
- help: {
533
- onDocument(doc) {
534
- doc[commandName] = { summary: i18n.t("start") };
535
- }
536
- }
537
- });
410
+ const commandName$3 = "cron:start";
411
+ const start = (opts) => {
412
+ return middleware.console({
413
+ fn: async (ctx, next) => {
414
+ if (ctx.input.command !== commandName$3) return next();
415
+ ctx.commandMatched = true;
416
+ if (!Number.isInteger(opts.port) || opts.port < 1 || opts.port > 65535) throw new Error(i18n.t("invalid_port", { port: opts.port }));
417
+ const crontab = await collectCrontab(opts);
418
+ const DELAY = 300;
419
+ if (!crontab.length) return;
420
+ const stopTasks = async (callback) => {
421
+ crontab.forEach((cron) => cron.stop());
422
+ let remain = crontab.length;
423
+ await Promise.all(crontab.map((cron) => {
424
+ const { promise, resolve } = Promise.withResolvers();
425
+ const timer = setInterval(() => {
426
+ if (!cron.runningLevel) {
427
+ clearInterval(timer);
428
+ resolve(void 0);
429
+ callback?.(--remain);
430
+ }
431
+ }, DELAY);
432
+ return promise;
433
+ }));
434
+ };
435
+ const collectRunners = () => {
436
+ return crontab.reduce((carry, cron) => carry.concat(cron.getPIDs().map((pid) => ({
437
+ pid,
438
+ command: cron.argv.join(" "),
439
+ schedule: cron.time
440
+ }))), []);
441
+ };
442
+ const sendStopMessages = async (socket) => {
443
+ socket.write(JSON.stringify({ runners: collectRunners() }) + "\n");
444
+ await stopTasks(() => {
445
+ socket.write(JSON.stringify({ runningPIDs: crontab.flatMap((cron) => cron.getPIDs()) }) + "\n");
446
+ });
447
+ socket.destroy();
448
+ };
449
+ const sendStatsMessage = (socket) => {
450
+ socket.write(JSON.stringify({ runners: collectRunners() }) + "\n");
451
+ };
452
+ const server = net.createServer(async (socket) => {
453
+ socket.on("data", async (data) => {
454
+ switch (data.toString()) {
455
+ case "cron:stop":
456
+ await sendStopMessages(socket);
457
+ break;
458
+ case "cron:stats": sendStatsMessage(socket);
459
+ }
460
+ });
461
+ socket.on("error", (err) => {
462
+ console.log(`[cron:start] ${err instanceof Error ? err.message : String(err)}`);
463
+ });
464
+ });
465
+ server.listen(opts.port);
466
+ process.once("SIGINT", async () => {
467
+ stopTasks();
468
+ });
469
+ await Promise.all(crontab.map((cron) => cron.start()));
470
+ await stopTasks();
471
+ await sleep(310);
472
+ server.close();
473
+ },
474
+ help: { onDocument(doc) {
475
+ doc[commandName$3] = { summary: i18n.t("start") };
476
+ } }
477
+ });
538
478
  };
539
-
540
479
  // src/middleware/eject.middleware.ts
541
- import { middleware as middleware2 } from "@aomex/common";
542
- var commandName2 = "cron:eject";
543
- var eject = (opts) => {
544
- return middleware2.console({
545
- fn: async (ctx, next) => {
546
- if (ctx.input.command !== commandName2) return next();
547
- ctx.commandMatched = true;
548
- const crontab = await collectCrontab(opts);
549
- console.log(crontab.map((cron2) => cron2.toString()).join("\n"));
550
- },
551
- help: {
552
- onDocument(doc) {
553
- doc[commandName2] = {
554
- summary: i18n.t("eject")
555
- };
556
- }
557
- }
558
- });
480
+ const commandName$2 = "cron:eject";
481
+ const eject = (opts) => {
482
+ return middleware.console({
483
+ fn: async (ctx, next) => {
484
+ if (ctx.input.command !== commandName$2) return next();
485
+ ctx.commandMatched = true;
486
+ const crontab = await collectCrontab(opts);
487
+ console.log(crontab.map((cron) => cron.toString()).join("\n"));
488
+ },
489
+ help: { onDocument(doc) {
490
+ doc[commandName$2] = { summary: i18n.t("eject") };
491
+ } }
492
+ });
559
493
  };
560
-
561
494
  // src/middleware/stop.middleware.ts
562
- import { terminal } from "@aomex/console";
563
- import { middleware as middleware3 } from "@aomex/common";
564
- import net2 from "net";
565
- import { bytes, sleep as sleep3 } from "@aomex/internal-tools";
566
- import formatDuration from "format-duration";
567
- import pidusage from "pidusage";
568
- var commandName3 = "cron:stop";
569
- var stop = (opts) => {
570
- return middleware3.console({
571
- fn: async (ctx, next) => {
572
- if (ctx.input.command !== commandName3) return next();
573
- ctx.commandMatched = true;
574
- const PORT = opts.port || DEFAULT_PORT;
575
- const client = net2.createConnection({ port: PORT }, () => {
576
- client.write(commandName3);
577
- });
578
- const logSession = terminal.createSession();
579
- let initialized = false;
580
- let runners = [];
581
- let timer;
582
- (function loop() {
583
- timer = setTimeout(async () => {
584
- let stats2;
585
- try {
586
- const pids = runners.filter(({ status }) => status === "loading").map(({ pid }) => pid);
587
- stats2 = pids.length ? await pidusage(pids) : {};
588
- } catch {
589
- stats2 = {};
590
- }
591
- runners = runners.map((runner) => {
592
- if (runner.status === "success") return runner;
593
- const stat = stats2[runner.pid];
594
- if (!stat) return runner;
595
- return {
596
- ...runner,
597
- cpu: stat.cpu,
598
- memory: stat.memory,
599
- elapsed: stat.elapsed
600
- };
601
- }).sort((a, b) => b.elapsed - a.elapsed);
602
- if (runners.length) {
603
- logSession.update(
604
- terminal.generateTable(
605
- [
606
- ["", "PID", "COMMAND", "SCHEDULE", "CPU", "MEMORY", "TIME"],
607
- ...runners.map(
608
- ({ pid, command, schedule, elapsed, cpu, memory, status }) => {
609
- return [
610
- `%${status}%`,
611
- pid,
612
- command.padEnd(24, " "),
613
- schedule,
614
- `${cpu.toFixed(2)}%`,
615
- bytes(memory),
616
- formatDuration(elapsed, { leading: true })
617
- ];
618
- }
619
- )
620
- ],
621
- {
622
- columnDefault: { paddingRight: 4 },
623
- columns: {
624
- 0: { paddingLeft: 0, paddingRight: 0 },
625
- 2: { paddingRight: 1, width: 24, wrapWord: true }
626
- },
627
- drawVerticalLine: () => false,
628
- drawHorizontalLine: () => false
629
- }
630
- ).replace(/^\s+/, " ")
631
- );
632
- }
633
- if (initialized && runners.every((item) => item.status === "success")) {
634
- logSession.commit();
635
- client.destroy();
636
- } else {
637
- loop();
638
- }
639
- }, 100);
640
- })();
641
- process.once("SIGINT", () => {
642
- clearTimeout(timer);
643
- client.destroy();
644
- });
645
- const { resolve, reject, promise } = Promise.withResolvers();
646
- client.on("close", resolve);
647
- client.on("error", (err) => {
648
- if (err.code === CONNECT_REFUSED) {
649
- terminal.printWarning(i18n.t("not_started", { port: PORT }));
650
- resolve(void 0);
651
- } else {
652
- reject(
653
- new Error(`[cron:stop] ${err instanceof Error ? err.message : String(err)}`)
654
- );
655
- }
656
- });
657
- client.on("data", async (data) => {
658
- for (const stringifyData of data.toString().split("\n").filter(Boolean)) {
659
- const jsonData = JSON.parse(stringifyData);
660
- if ("runners" in jsonData) {
661
- initialized = true;
662
- runners = jsonData.runners.map((runner) => {
663
- return {
664
- ...runner,
665
- cpu: 0,
666
- memory: 0,
667
- elapsed: 0,
668
- status: "loading"
669
- };
670
- });
671
- } else if ("runningPIDs" in jsonData) {
672
- runners.forEach((item) => {
673
- if (!jsonData.runningPIDs.includes(item.pid)) {
674
- item.status = "success";
675
- }
676
- });
677
- }
678
- }
679
- });
680
- await promise;
681
- await sleep3(300);
682
- },
683
- help: {
684
- onDocument(doc) {
685
- doc[commandName3] = { summary: i18n.t("stop") };
686
- }
687
- }
688
- });
495
+ const commandName$1 = "cron:stop";
496
+ const stop = (opts) => {
497
+ return middleware.console({
498
+ fn: async (ctx, next) => {
499
+ if (ctx.input.command !== commandName$1) return next();
500
+ ctx.commandMatched = true;
501
+ const { port } = opts;
502
+ const client = net.createConnection({ port }, () => {
503
+ client.write(commandName$1);
504
+ });
505
+ const logSession = terminal.createSession();
506
+ let initialized = false;
507
+ let runners = [];
508
+ let timer;
509
+ (function loop() {
510
+ timer = setTimeout(async () => {
511
+ let stats;
512
+ try {
513
+ const pids = runners.filter(({ status }) => status === "loading").map(({ pid }) => pid);
514
+ stats = pids.length ? await pidusage(pids) : {};
515
+ } catch {
516
+ stats = {};
517
+ }
518
+ runners = runners.map((runner) => {
519
+ if (runner.status === "success") return runner;
520
+ const stat = stats[runner.pid];
521
+ if (!stat) return runner;
522
+ return {
523
+ ...runner,
524
+ cpu: stat.cpu,
525
+ memory: stat.memory,
526
+ elapsed: stat.elapsed
527
+ };
528
+ }).sort((a, b) => b.elapsed - a.elapsed);
529
+ if (runners.length) logSession.update(terminal.generateTable([[
530
+ "",
531
+ "PID",
532
+ "COMMAND",
533
+ "SCHEDULE",
534
+ "CPU",
535
+ "MEMORY",
536
+ "TIME"
537
+ ], ...runners.map(({ pid, command, schedule, elapsed, cpu, memory, status }) => {
538
+ return [
539
+ `%${status}%`,
540
+ pid,
541
+ command.padEnd(24, " "),
542
+ schedule,
543
+ `${cpu.toFixed(2)}%`,
544
+ bytes(memory),
545
+ formatDuration(elapsed, { leading: true })
546
+ ];
547
+ })], {
548
+ columnDefault: { paddingRight: 4 },
549
+ columns: {
550
+ 0: {
551
+ paddingLeft: 0,
552
+ paddingRight: 0
553
+ },
554
+ 2: {
555
+ paddingRight: 1,
556
+ width: 24,
557
+ wrapWord: true
558
+ }
559
+ },
560
+ drawVerticalLine: () => false,
561
+ drawHorizontalLine: () => false
562
+ }).replace(/^\s+/, " "));
563
+ if (initialized && runners.every((item) => item.status === "success")) {
564
+ logSession.commit();
565
+ client.destroy();
566
+ } else loop();
567
+ }, 100);
568
+ })();
569
+ process.once("SIGINT", () => {
570
+ clearTimeout(timer);
571
+ client.destroy();
572
+ });
573
+ const { resolve, reject, promise } = Promise.withResolvers();
574
+ client.on("close", resolve);
575
+ client.on("error", (err) => {
576
+ if (err.code === "ECONNREFUSED") {
577
+ terminal.printWarning(i18n.t("not_started", { port }));
578
+ resolve(void 0);
579
+ } else reject(/* @__PURE__ */ new Error(`[cron:stop] ${err instanceof Error ? err.message : String(err)}`));
580
+ });
581
+ client.on("data", async (data) => {
582
+ for (const stringifyData of data.toString().split("\n").filter(Boolean)) {
583
+ const jsonData = JSON.parse(stringifyData);
584
+ if ("runners" in jsonData) {
585
+ initialized = true;
586
+ runners = jsonData.runners.map((runner) => {
587
+ return {
588
+ ...runner,
589
+ cpu: 0,
590
+ memory: 0,
591
+ elapsed: 0,
592
+ status: "loading"
593
+ };
594
+ });
595
+ } else if ("runningPIDs" in jsonData) runners.forEach((item) => {
596
+ if (!jsonData.runningPIDs.includes(item.pid)) item.status = "success";
597
+ });
598
+ }
599
+ });
600
+ await promise;
601
+ await sleep$1(300);
602
+ },
603
+ help: { onDocument(doc) {
604
+ doc[commandName$1] = { summary: i18n.t("stop") };
605
+ } }
606
+ });
689
607
  };
690
-
691
608
  // src/middleware/stats.middleware.ts
692
- import { terminal as terminal2 } from "@aomex/console";
693
- import { middleware as middleware4 } from "@aomex/common";
694
- import net3 from "net";
695
- import pidusage2 from "pidusage";
696
- import { bytes as bytes2 } from "@aomex/internal-tools";
697
- import formatDuration2 from "format-duration";
698
- var commandName4 = "cron:stats";
699
- var stats = (opts) => {
700
- return middleware4.console({
701
- fn: async (ctx, next) => {
702
- if (ctx.input.command !== commandName4) return next();
703
- ctx.commandMatched = true;
704
- const PORT = opts.port || DEFAULT_PORT;
705
- const client = net3.createConnection({ port: PORT }, () => {
706
- client.write(commandName4);
707
- const timer = setInterval(() => {
708
- client.write(commandName4);
709
- }, 600);
710
- client.on("error", () => {
711
- clearInterval(timer);
712
- });
713
- client.on("close", () => {
714
- clearInterval(timer);
715
- });
716
- });
717
- const logSession = terminal2.createSession();
718
- const { resolve, reject, promise } = Promise.withResolvers();
719
- client.on("close", resolve);
720
- client.on("error", (err) => {
721
- if (err.code === CONNECT_REFUSED) {
722
- terminal2.printWarning(i18n.t("not_started", { port: PORT }));
723
- resolve(void 0);
724
- } else {
725
- reject(err);
726
- }
727
- });
728
- client.on("data", async (data) => {
729
- for (const stringifyData of data.toString().split("\n").filter(Boolean)) {
730
- const jsonData = JSON.parse(stringifyData);
731
- if (!("runners" in jsonData)) return;
732
- let stats2;
733
- try {
734
- stats2 = await pidusage2(jsonData.runners.map((item) => item.pid));
735
- } catch {
736
- stats2 = {};
737
- }
738
- logSession.update(
739
- terminal2.generateTable(
740
- [
741
- ["PID", "COMMAND", "SCHEDULE", "CPU", "MEMORY", "TIME"],
742
- ...jsonData.runners.map((runner) => {
743
- const stat = stats2[runner.pid] || { cpu: 0, memory: 0, elapsed: 0 };
744
- return { ...runner, ...stat };
745
- }).sort((a, b) => b.elapsed - a.elapsed).map(({ pid, command, schedule, elapsed, cpu, memory }) => {
746
- return [
747
- pid,
748
- command.padEnd(24, " "),
749
- schedule,
750
- `${cpu.toFixed(2)}%`,
751
- bytes2(memory),
752
- formatDuration2(elapsed, { leading: true })
753
- ];
754
- })
755
- ],
756
- {
757
- columnDefault: { paddingRight: 4 },
758
- columns: {
759
- 1: {
760
- paddingRight: 1,
761
- width: 24,
762
- wrapWord: true
763
- }
764
- },
765
- drawVerticalLine: () => false,
766
- drawHorizontalLine: () => false
767
- }
768
- )
769
- );
770
- }
771
- });
772
- await promise;
773
- },
774
- help: {
775
- onDocument(doc) {
776
- doc[commandName4] = { summary: i18n.t("stats") };
777
- }
778
- }
779
- });
609
+ const commandName = "cron:stats";
610
+ const stats = (opts) => {
611
+ return middleware.console({
612
+ fn: async (ctx, next) => {
613
+ if (ctx.input.command !== commandName) return next();
614
+ ctx.commandMatched = true;
615
+ const { port } = opts;
616
+ const client = net.createConnection({ port }, () => {
617
+ client.write(commandName);
618
+ const timer = setInterval(() => {
619
+ client.write(commandName);
620
+ }, 600);
621
+ client.on("error", () => {
622
+ clearInterval(timer);
623
+ });
624
+ client.on("close", () => {
625
+ clearInterval(timer);
626
+ });
627
+ });
628
+ const logSession = terminal.createSession();
629
+ const { resolve, reject, promise } = Promise.withResolvers();
630
+ client.on("close", resolve);
631
+ client.on("error", (err) => {
632
+ if (err.code === "ECONNREFUSED") {
633
+ terminal.printWarning(i18n.t("not_started", { port }));
634
+ resolve(void 0);
635
+ } else reject(err);
636
+ });
637
+ client.on("data", async (data) => {
638
+ for (const stringifyData of data.toString().split("\n").filter(Boolean)) {
639
+ const jsonData = JSON.parse(stringifyData);
640
+ if (!("runners" in jsonData)) return;
641
+ let stats;
642
+ try {
643
+ stats = await pidusage(jsonData.runners.map((item) => item.pid));
644
+ } catch {
645
+ stats = {};
646
+ }
647
+ logSession.update(terminal.generateTable([[
648
+ "PID",
649
+ "COMMAND",
650
+ "SCHEDULE",
651
+ "CPU",
652
+ "MEMORY",
653
+ "TIME"
654
+ ], ...jsonData.runners.map((runner) => {
655
+ const stat = stats[runner.pid] || {
656
+ cpu: 0,
657
+ memory: 0,
658
+ elapsed: 0
659
+ };
660
+ return {
661
+ ...runner,
662
+ ...stat
663
+ };
664
+ }).sort((a, b) => b.elapsed - a.elapsed).map(({ pid, command, schedule, elapsed, cpu, memory }) => {
665
+ return [
666
+ pid,
667
+ command.padEnd(24, " "),
668
+ schedule,
669
+ `${cpu.toFixed(2)}%`,
670
+ bytes(memory),
671
+ formatDuration(elapsed, { leading: true })
672
+ ];
673
+ })], {
674
+ columnDefault: { paddingRight: 4 },
675
+ columns: { 1: {
676
+ paddingRight: 1,
677
+ width: 24,
678
+ wrapWord: true
679
+ } },
680
+ drawVerticalLine: () => false,
681
+ drawHorizontalLine: () => false
682
+ }));
683
+ }
684
+ });
685
+ await promise;
686
+ },
687
+ help: { onDocument(doc) {
688
+ doc[commandName] = { summary: i18n.t("stats") };
689
+ } }
690
+ });
780
691
  };
781
-
782
692
  // src/middleware/crons.middleware.ts
783
- var crons = (opts) => {
784
- const middlewareList = [start(opts), eject(opts), stop(opts), stats(opts)];
785
- const fn = compose(middlewareList);
786
- return middleware5.console({
787
- fn,
788
- help: {
789
- async onDocument(_, { children }) {
790
- await children(middlewareList);
791
- },
792
- async postDocument(_, { children }) {
793
- await children(middlewareList);
794
- }
795
- }
796
- });
797
- };
798
- export {
799
- CronMiddleware,
800
- cron,
801
- crons
693
+ const crons = (opts) => {
694
+ const middlewareList = [
695
+ start(opts),
696
+ eject(opts),
697
+ stop(opts),
698
+ stats(opts)
699
+ ];
700
+ const fn = compose(middlewareList);
701
+ return middleware.console({
702
+ fn,
703
+ help: {
704
+ async onDocument(_, { children }) {
705
+ await children(middlewareList);
706
+ },
707
+ async postDocument(_, { children }) {
708
+ await children(middlewareList);
709
+ }
710
+ }
711
+ });
802
712
  };
713
+ export { CronMiddleware, cron, crons };
714
+
803
715
  //# sourceMappingURL=index.js.map