krontab 0.1.1 → 0.1.2
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.cjs +763 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +733 -7
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,734 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
import { performance } from "node:perf_hooks";
|
|
2
|
+
import path, { delimiter, extname, join, relative, resolve } from "node:path";
|
|
3
|
+
import fs, { existsSync, mkdirSync, realpathSync, statSync } from "node:fs";
|
|
4
|
+
import { env } from "node:process";
|
|
5
|
+
import { CronExpressionParser } from "cron-parser";
|
|
6
|
+
import { open, readFile, stat } from "node:fs/promises";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import net from "node:net";
|
|
10
|
+
|
|
11
|
+
// src/consts.ts
|
|
12
|
+
let Marker;
|
|
13
|
+
(function(_Marker) {
|
|
14
|
+
_Marker.CRON = "@cron";
|
|
15
|
+
_Marker.REGEX = /@cron\b/;
|
|
16
|
+
_Marker.BEGIN = "@cronbegin";
|
|
17
|
+
_Marker.BEGIN_REGEX = /@cronbegin\b/;
|
|
18
|
+
_Marker.END = "@cronend";
|
|
19
|
+
_Marker.END_REGEX = /@cronend\b/;
|
|
20
|
+
_Marker.UTC = "@cronutc";
|
|
21
|
+
_Marker.UTC_REGEX = /@cronutc\b/;
|
|
22
|
+
})(Marker || (Marker = {}));
|
|
23
|
+
|
|
24
|
+
// src/context/interpreter.ts
|
|
25
|
+
const isPath = (cmd) => cmd.includes("/") || cmd.includes("\\");
|
|
26
|
+
/**
|
|
27
|
+
* 检测系统中可用的运行时命令。
|
|
28
|
+
* - 只查 PATH、不执行命令:`tsx --version` 实测约 740ms,而探测在 cronjob() 的启动路径上,
|
|
29
|
+
* 每个 cx 都要付一次太贵。代价是"存在但跑不起来"的命令会被当成可用,启动时不会发现。
|
|
30
|
+
* - 含路径分隔符的命令直接看文件是否存在,不查 PATH
|
|
31
|
+
* - PATH 为空时(某些 pm2 配置)回退到常见系统目录
|
|
32
|
+
* @returns 可用的命令名,都不可用则返回 null
|
|
33
|
+
*/
|
|
34
|
+
function detectCommand(cmd) {
|
|
35
|
+
if (isPath(cmd)) return existsSync(cmd) ? cmd : null;
|
|
36
|
+
for (const dir of (env.PATH || "/usr/local/bin:/usr/bin:/bin").split(delimiter)) if (dir && existsSync(join(dir, cmd))) return cmd;
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
/** 标记"没有可用解释器"的占位命令,run() 见到它只记 WARN 不 spawn */
|
|
40
|
+
const CMD_NONE = "none";
|
|
41
|
+
/**
|
|
42
|
+
* 探测所有运行时,返回解释器映射表。
|
|
43
|
+
*/
|
|
44
|
+
function detectRuntime() {
|
|
45
|
+
const tsCmd = detectCommand("tsx") ?? detectCommand("ts-node") ?? process.execPath;
|
|
46
|
+
const jsLike = (cmd) => ({
|
|
47
|
+
cmd,
|
|
48
|
+
args: []
|
|
49
|
+
});
|
|
50
|
+
const interpreters = {
|
|
51
|
+
".ts": jsLike(tsCmd),
|
|
52
|
+
".mts": jsLike(tsCmd),
|
|
53
|
+
".cts": jsLike(tsCmd),
|
|
54
|
+
".js": jsLike(process.execPath),
|
|
55
|
+
".mjs": jsLike(process.execPath),
|
|
56
|
+
".cjs": jsLike(process.execPath),
|
|
57
|
+
".py": {
|
|
58
|
+
cmd: detectCommand("python3") || detectCommand("python") || "none",
|
|
59
|
+
args: []
|
|
60
|
+
},
|
|
61
|
+
".sh": {
|
|
62
|
+
cmd: detectCommand("bash") || "sh",
|
|
63
|
+
args: []
|
|
64
|
+
},
|
|
65
|
+
none: {
|
|
66
|
+
cmd: CMD_NONE,
|
|
67
|
+
args: []
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
return {
|
|
71
|
+
interpreters,
|
|
72
|
+
hasTsx: tsCmd !== process.execPath,
|
|
73
|
+
pythonCmd: interpreters[".py"].cmd
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** 取扩展名对应的解释器;没有映射的(或映射成 none)交给 run() 记 WARN */
|
|
77
|
+
function getDefaultInterpreter(runtime, ext) {
|
|
78
|
+
return runtime.interpreters[ext] || runtime.interpreters.none;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/context/logger.ts
|
|
82
|
+
/**
|
|
83
|
+
* 把 cx.write 包装成带 tag 的方法。
|
|
84
|
+
* - write 是唯一的输出出口,消费者可以整条替换(默认写 stdout)
|
|
85
|
+
*/
|
|
86
|
+
function createLogger(write) {
|
|
87
|
+
return {
|
|
88
|
+
info: (...args) => write("[INFO]", ...args),
|
|
89
|
+
err: (...args) => write("[ERROR]", ...args),
|
|
90
|
+
warn: (...args) => write("[WARN]", ...args),
|
|
91
|
+
spawn: (...args) => write("[SPAWN]", ...args),
|
|
92
|
+
exit: (...args) => write("[EXIT]", ...args),
|
|
93
|
+
debug: (...args) => write("[DEBUG]", ...args)
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/** 默认输出:`<dtm> <TAG> <内容>`,dtm 用 cx.timezone */
|
|
97
|
+
function defaultWrite(formatter) {
|
|
98
|
+
return (tag, ...args) => console.log(formatter.format(/* @__PURE__ */ new Date()), tag, ...args);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/context/index.ts
|
|
102
|
+
/** 默认值:只改一处,测试与 createContext 都从这里断言 */
|
|
103
|
+
const DEFAULTS = {
|
|
104
|
+
include: ["**/*.{ts,js,sh}"],
|
|
105
|
+
exclude: [
|
|
106
|
+
"**/node_modules/",
|
|
107
|
+
"**/.git/",
|
|
108
|
+
"**/.vscode/",
|
|
109
|
+
"**/.claude/",
|
|
110
|
+
"**/__pycache__/",
|
|
111
|
+
"**/dist/",
|
|
112
|
+
"**/dist-tsc/",
|
|
113
|
+
"**/coverage/"
|
|
114
|
+
],
|
|
115
|
+
timezone: "Asia/Shanghai"
|
|
116
|
+
};
|
|
117
|
+
const createFormatter = (timezone) => new Intl.DateTimeFormat("zh-CN", {
|
|
118
|
+
year: "numeric",
|
|
119
|
+
month: "2-digit",
|
|
120
|
+
day: "2-digit",
|
|
121
|
+
hour: "2-digit",
|
|
122
|
+
minute: "2-digit",
|
|
123
|
+
second: "2-digit",
|
|
124
|
+
fractionalSecondDigits: 3,
|
|
125
|
+
hour12: false,
|
|
126
|
+
timeZone: timezone
|
|
127
|
+
});
|
|
128
|
+
/**
|
|
129
|
+
* 创建上下文:配置校验 + 默认值 + 格式化器 + logger + 运行时映射,一次给齐。
|
|
130
|
+
* - `runtime` 由调用方传入时直接用(便于测试注入);不传就现场探测一次
|
|
131
|
+
* - 探测只查 PATH(见 interpreter.ts),不执行外部命令
|
|
132
|
+
*/
|
|
133
|
+
function createContext(rawConfig, runtime = detectRuntime()) {
|
|
134
|
+
const { dir = process.cwd(), logDir = dir, jobcwd = dir, include = DEFAULTS.include, exclude = DEFAULTS.exclude, timezone = DEFAULTS.timezone, write } = Object(rawConfig);
|
|
135
|
+
if (typeof dir !== "string") throw new TypeError("`dir` must be a string");
|
|
136
|
+
if (typeof logDir !== "string") throw new TypeError("`logDir` must be a string");
|
|
137
|
+
if (typeof jobcwd !== "string" && typeof jobcwd !== "function") throw new TypeError("`jobcwd` must be a string or a function");
|
|
138
|
+
if (write !== void 0 && typeof write !== "function") throw new TypeError("`write` must be a function");
|
|
139
|
+
new Intl.DateTimeFormat("en-US", { timeZone: timezone });
|
|
140
|
+
if (!Array.isArray(include) || include.some((pattern) => typeof pattern !== "string")) throw new TypeError("`include` must be an array of strings");
|
|
141
|
+
if (!Array.isArray(exclude) || exclude.some((pattern) => typeof pattern !== "string")) throw new TypeError("`exclude` must be an array of strings");
|
|
142
|
+
const absDir = resolve(dir);
|
|
143
|
+
const absLogDir = resolve(logDir);
|
|
144
|
+
const timeFormat = createFormatter(timezone);
|
|
145
|
+
const defaultJobcwd = typeof jobcwd !== "function" && jobcwd === dir ? absDir : jobcwd;
|
|
146
|
+
const jobcwdFn = typeof defaultJobcwd === "function" ? defaultJobcwd : () => defaultJobcwd;
|
|
147
|
+
const writer = write === void 0 ? defaultWrite(timeFormat) : write;
|
|
148
|
+
return {
|
|
149
|
+
dir: absDir,
|
|
150
|
+
logDir: absLogDir,
|
|
151
|
+
jobcwd: jobcwdFn,
|
|
152
|
+
include,
|
|
153
|
+
exclude,
|
|
154
|
+
timezone,
|
|
155
|
+
timeFormat,
|
|
156
|
+
runtime,
|
|
157
|
+
jobState: 0,
|
|
158
|
+
jobTimer: null,
|
|
159
|
+
write: writer,
|
|
160
|
+
log: createLogger(writer)
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// src/utils.ts
|
|
165
|
+
/**
|
|
166
|
+
* 返回要处理的文件的绝对路径
|
|
167
|
+
*/
|
|
168
|
+
const tryGlobSync = (cx) => {
|
|
169
|
+
try {
|
|
170
|
+
return fs.globSync(cx.include, {
|
|
171
|
+
cwd: cx.dir,
|
|
172
|
+
exclude: cx.exclude
|
|
173
|
+
}).map((v) => path.resolve(cx.dir, v));
|
|
174
|
+
} catch (e) {
|
|
175
|
+
cx.log.err(`Error while globbing scripts.`, e);
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
// src/cron/task.ts
|
|
181
|
+
/** 下一分钟边界(本地毫秒截断到分钟) */
|
|
182
|
+
const nextMinuteBoundary = (from) => {
|
|
183
|
+
const next = new Date(from.getTime() + 6e4);
|
|
184
|
+
next.setSeconds(0, 0);
|
|
185
|
+
return next;
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* 每分钟执行一次 fn,返回控制对象
|
|
189
|
+
* - 状态全部放在 cx.jobState / cx.jobTimer 里,本函数不持有模块级状态
|
|
190
|
+
* - 每次调度都重新读 cx.jobState,因此 stop/resume 在任意时刻都生效
|
|
191
|
+
*/
|
|
192
|
+
function runTask(cx, fn) {
|
|
193
|
+
const schedule = () => {
|
|
194
|
+
if (cx.jobState === 2) return;
|
|
195
|
+
const now = /* @__PURE__ */ new Date();
|
|
196
|
+
const nextMinute = nextMinuteBoundary(now);
|
|
197
|
+
cx.jobTimer = setTimeout(() => {
|
|
198
|
+
cx.jobTimer = null;
|
|
199
|
+
if (cx.jobState === 2) return;
|
|
200
|
+
if (cx.jobState === 1) {
|
|
201
|
+
schedule();
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
//! 定时器可能早于边界触发,相当于等了但还没等到呢,再等一会
|
|
205
|
+
if (Date.now() < nextMinute.getTime()) {
|
|
206
|
+
schedule();
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const noSecondDate = /* @__PURE__ */ new Date();
|
|
210
|
+
noSecondDate.setSeconds(0, 0);
|
|
211
|
+
schedule();
|
|
212
|
+
try {
|
|
213
|
+
const ret = fn(noSecondDate);
|
|
214
|
+
if (ret && typeof ret.catch === "function") ret.catch((e) => cx.log.err(`Task tick failed:`, e));
|
|
215
|
+
} catch (e) {
|
|
216
|
+
cx.log.err(`Task tick failed:`, e);
|
|
217
|
+
}
|
|
218
|
+
}, nextMinute.getTime() - now.getTime());
|
|
219
|
+
};
|
|
220
|
+
schedule();
|
|
221
|
+
return {
|
|
222
|
+
stop() {
|
|
223
|
+
if (cx.jobTimer) {
|
|
224
|
+
clearTimeout(cx.jobTimer);
|
|
225
|
+
cx.jobTimer = null;
|
|
226
|
+
}
|
|
227
|
+
cx.jobState = 2;
|
|
228
|
+
},
|
|
229
|
+
pause() {
|
|
230
|
+
if (cx.jobState === 0) cx.jobState = 1;
|
|
231
|
+
},
|
|
232
|
+
resume() {
|
|
233
|
+
if (cx.jobState === 2) return;
|
|
234
|
+
cx.jobState = 0;
|
|
235
|
+
if (cx.jobTimer === null) schedule();
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// src/cron/parse.ts
|
|
241
|
+
/**
|
|
242
|
+
* 非得要try很奇怪,但这是官方推荐的方式
|
|
243
|
+
*
|
|
244
|
+
* @param timezone cron 语义使用的时区;默认是 cx.timezone,`@cronutc` 之后传 'UTC'
|
|
245
|
+
*/
|
|
246
|
+
const parseExp = (cx, exp, filepath, timezone = cx.timezone) => {
|
|
247
|
+
try {
|
|
248
|
+
return CronExpressionParser.parse(exp, {
|
|
249
|
+
tz: timezone,
|
|
250
|
+
hashSeed: filepath
|
|
251
|
+
});
|
|
252
|
+
} catch {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
/**
|
|
257
|
+
* 判断给定日期是否匹配 cron 表达式
|
|
258
|
+
* @param expression cron 表达式
|
|
259
|
+
* @param d 待匹配的日期
|
|
260
|
+
*/
|
|
261
|
+
function matches(expression, d) {
|
|
262
|
+
return expression.includesDate(d);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// src/syntax/allow.ts
|
|
266
|
+
/**
|
|
267
|
+
* ! 多行注释以`*`开头是实时标准和社区、行业规范
|
|
268
|
+
*/
|
|
269
|
+
const jstsAllow = (line) => line.startsWith("//") || line.startsWith("/*") || line.startsWith("*") || line.startsWith("*/") || line.length === 0;
|
|
270
|
+
const allows = {
|
|
271
|
+
".ts": jstsAllow,
|
|
272
|
+
".mts": jstsAllow,
|
|
273
|
+
".cts": jstsAllow,
|
|
274
|
+
".js": jstsAllow,
|
|
275
|
+
".mjs": jstsAllow,
|
|
276
|
+
".cjs": jstsAllow,
|
|
277
|
+
".py": (line) => /^(#|'''|""")/.test(line) || line.length === 0,
|
|
278
|
+
".sh": (line) => line.startsWith("#") || line.length === 0
|
|
279
|
+
};
|
|
280
|
+
function getAllowFn(ext) {
|
|
281
|
+
return allows[ext] || (() => false);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// src/syntax/shebang.ts
|
|
285
|
+
const parse = (text) => {
|
|
286
|
+
const [cmd, ...args] = text.split(/\s+/).filter(Boolean);
|
|
287
|
+
return cmd ? {
|
|
288
|
+
cmd,
|
|
289
|
+
args
|
|
290
|
+
} : null;
|
|
291
|
+
};
|
|
292
|
+
/**
|
|
293
|
+
* 获取解释器,同时也可用于判定是否存在 shebang
|
|
294
|
+
* - 如果有人只是在第一行写了"#!",后面没写任何东西,这里也会返回`null`
|
|
295
|
+
*/
|
|
296
|
+
const getShebang = (line) => line.startsWith("#!") ? parse(line.slice(2)) : null;
|
|
297
|
+
|
|
298
|
+
// src/syntax/extract.ts
|
|
299
|
+
/**
|
|
300
|
+
* 从一行文本中提取带标记的 cron 表达式
|
|
301
|
+
* - 只接受5位表达式,不支持秒级
|
|
302
|
+
* - `@cronutc <5 段>` 是行内指令:这一条按 UTC 解析,不影响其它行
|
|
303
|
+
*
|
|
304
|
+
* @param trimmedLine 已经去掉前导空格的行文本
|
|
305
|
+
* @param inBlock 是否在 @cronbegin 和 @cronend 块中
|
|
306
|
+
* @param relativePath 相对路径,用于日志输出
|
|
307
|
+
*/
|
|
308
|
+
function extractCron(cx, trimmedLine, inBlock, relativePath) {
|
|
309
|
+
if (trimmedLine.search(Marker.BEGIN_REGEX) !== -1) return Marker.BEGIN;
|
|
310
|
+
if (trimmedLine.search(Marker.END_REGEX) !== -1) return Marker.END;
|
|
311
|
+
const index = trimmedLine.search(Marker.REGEX);
|
|
312
|
+
const utcIndex = trimmedLine.search(Marker.UTC_REGEX);
|
|
313
|
+
if (index !== -1 && utcIndex !== -1) {
|
|
314
|
+
cx.log.err(`Line contains both ${Marker.CRON} and ${Marker.UTC}, nothing scheduled: ${relativePath}`);
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
let timezone = cx.timezone;
|
|
318
|
+
let expStart = -1;
|
|
319
|
+
if (index !== -1) expStart = index + Marker.CRON.length;
|
|
320
|
+
else if (utcIndex !== -1) {
|
|
321
|
+
timezone = "UTC";
|
|
322
|
+
expStart = utcIndex + Marker.UTC.length;
|
|
323
|
+
}
|
|
324
|
+
if (expStart === -1) {
|
|
325
|
+
if (inBlock) cx.log.warn(`@cron should be used to mark cron expressions in cron blocks: ${relativePath}`);
|
|
326
|
+
return null;
|
|
327
|
+
}
|
|
328
|
+
const tokens = trimmedLine.slice(expStart).split(/\s+/).filter(Boolean);
|
|
329
|
+
//! 阻止cron-parser 把 4 段自动补齐成另一条合法表达式
|
|
330
|
+
if (tokens.length < 5) {
|
|
331
|
+
cx.log.err(`Invalid cron expression: "${tokens.join(" ")}" in file: ${relativePath}`);
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
if (tokens.length >= 6) {
|
|
335
|
+
const sixExpStr = tokens.slice(0, 6).join(" ");
|
|
336
|
+
if (parseExp(cx, sixExpStr, relativePath, timezone)) {
|
|
337
|
+
cx.log.err(`6 fields cron is not supported, use 5 fields instead. Found "${sixExpStr}" in file: ${relativePath}`);
|
|
338
|
+
return null;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
const cron = parseExp(cx, tokens.slice(0, 5).join(" "), relativePath, timezone);
|
|
342
|
+
return cron ? {
|
|
343
|
+
cron,
|
|
344
|
+
timezone
|
|
345
|
+
} : null;
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* 从文件内容提取带标记的 cron 表达式,并组合成`JobItem`,一次性提供
|
|
349
|
+
* cron表达式对象、分组信息、文件路径以及解释器信息
|
|
350
|
+
*
|
|
351
|
+
* @param filepath 文件路径,用于日志输出
|
|
352
|
+
* @param content 文件头内容(可以是整文件;第一行正式代码之后的不会用到)
|
|
353
|
+
*/
|
|
354
|
+
function getJobItem(cx, filepath, content) {
|
|
355
|
+
const ext = extname(filepath);
|
|
356
|
+
const allowFn = getAllowFn(ext);
|
|
357
|
+
let lines = content.split("\n").map((line) => line.trim());
|
|
358
|
+
if (lines.length === 0) return null;
|
|
359
|
+
const shebang = getShebang(lines[0]);
|
|
360
|
+
if (shebang) lines.shift();
|
|
361
|
+
if (lines.length === 0) return null;
|
|
362
|
+
const firstNotAllowedIndex = lines.findIndex((v) => !allowFn(v));
|
|
363
|
+
if (firstNotAllowedIndex !== -1) lines = lines.slice(0, firstNotAllowedIndex);
|
|
364
|
+
if (lines.length === 0) return null;
|
|
365
|
+
const list = [];
|
|
366
|
+
const relativePath = relative(cx.dir, filepath);
|
|
367
|
+
let inCronBlock = false;
|
|
368
|
+
let group = 0;
|
|
369
|
+
for (const line of lines) {
|
|
370
|
+
const extracted = extractCron(cx, line, inCronBlock, relativePath);
|
|
371
|
+
if (!extracted) continue;
|
|
372
|
+
if (extracted === Marker.BEGIN) {
|
|
373
|
+
if (inCronBlock) {
|
|
374
|
+
cx.log.err(`Nested ${Marker.BEGIN} found in file: ${relativePath}`);
|
|
375
|
+
return null;
|
|
376
|
+
}
|
|
377
|
+
group++;
|
|
378
|
+
inCronBlock = true;
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
if (extracted === Marker.END) {
|
|
382
|
+
if (!inCronBlock) {
|
|
383
|
+
cx.log.err(`${Marker.END} didn't match ${Marker.BEGIN} in file: ${relativePath}`);
|
|
384
|
+
return null;
|
|
385
|
+
}
|
|
386
|
+
inCronBlock = false;
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
list.push({
|
|
390
|
+
...extracted,
|
|
391
|
+
group: inCronBlock ? group : 0
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
if (inCronBlock) {
|
|
395
|
+
cx.log.err(`Unclosed ${Marker.BEGIN}/${Marker.END} block in file: ${relativePath}`);
|
|
396
|
+
return null;
|
|
397
|
+
}
|
|
398
|
+
return {
|
|
399
|
+
flatCronGroups: list,
|
|
400
|
+
interpreter: shebang ?? getDefaultInterpreter(cx.runtime, ext),
|
|
401
|
+
filepath
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// src/syntax/header.ts
|
|
406
|
+
/** 文件头最多读 64KB;比这小的文件由调用方直接整读 */
|
|
407
|
+
const MAX_HEADER = 65536;
|
|
408
|
+
/**
|
|
409
|
+
* 只读大文件的前 MAX_HEADER 字节,一次定位读,不循环。
|
|
410
|
+
* - 读出来的内容可能带上一行正式代码或半行,没关系:getJobItem 会在第一行正式代码处切掉
|
|
411
|
+
* - 只有前 64KB 全是注释(说明文件头真的超长)才记 WARN,避免每个大文件每分钟刷一条
|
|
412
|
+
*/
|
|
413
|
+
async function readHeader(cx, filepath, allowLine) {
|
|
414
|
+
const s = await stat(filepath);
|
|
415
|
+
if (!s.isFile()) {
|
|
416
|
+
cx.log.warn(`Skipped non-regular file: ${path.relative(cx.dir, filepath)}`);
|
|
417
|
+
return null;
|
|
418
|
+
}
|
|
419
|
+
if (s.size < 65536) return await readFile(filepath, "utf8");
|
|
420
|
+
const fh = await open(filepath, "r");
|
|
421
|
+
try {
|
|
422
|
+
const buf = Buffer.alloc(MAX_HEADER);
|
|
423
|
+
const { bytesRead } = await fh.read(buf, 0, MAX_HEADER, 0);
|
|
424
|
+
const text = buf.subarray(0, bytesRead).toString("utf8");
|
|
425
|
+
if (bytesRead === 65536 && text.split("\n").every((line) => allowLine(line.trim()))) cx.log.warn(`Header longer than ${MAX_HEADER} bytes, truncated: ${path.relative(cx.dir, filepath)}`);
|
|
426
|
+
return text;
|
|
427
|
+
} finally {
|
|
428
|
+
await fh.close();
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// src/syntax/job.ts
|
|
433
|
+
const CHUNK_SIZE = 100;
|
|
434
|
+
/**
|
|
435
|
+
* stat 并读取文件头,一个文件对应一条结果,失败也包成结果、不抛出。
|
|
436
|
+
* - 先 stat:FIFO、设备、目录等非普通文件直接跳过(对 FIFO 做 readFile 会永久阻塞线程池)
|
|
437
|
+
* - 只读文件头:大文件不再整读进内存
|
|
438
|
+
*/
|
|
439
|
+
async function loadFiles(cx, filepaths) {
|
|
440
|
+
const result = [];
|
|
441
|
+
for (let i = 0; i < filepaths.length; i += CHUNK_SIZE) {
|
|
442
|
+
const promises = filepaths.slice(i, i + CHUNK_SIZE).map(async (filepath) => {
|
|
443
|
+
try {
|
|
444
|
+
const allower = getAllowFn(path.extname(filepath));
|
|
445
|
+
return {
|
|
446
|
+
filepath,
|
|
447
|
+
content: await readHeader(cx, filepath, allower),
|
|
448
|
+
error: null
|
|
449
|
+
};
|
|
450
|
+
} catch (error) {
|
|
451
|
+
return {
|
|
452
|
+
filepath,
|
|
453
|
+
content: null,
|
|
454
|
+
error
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
const r = await Promise.all(promises);
|
|
459
|
+
result.push(...r);
|
|
460
|
+
}
|
|
461
|
+
return result;
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* 获取现在应该运行的job
|
|
465
|
+
* - 不会有人写非常多的 cron 表达式,直接遍历即可
|
|
466
|
+
*
|
|
467
|
+
* ! 仅用于同一个filepath
|
|
468
|
+
*
|
|
469
|
+
* @param cx Cronjob 上下文
|
|
470
|
+
* @param item JobItem 对象
|
|
471
|
+
* @param now 当前时间,**秒数、毫秒数为0**
|
|
472
|
+
*/
|
|
473
|
+
function getMatchedJob(cx, item, now) {
|
|
474
|
+
let count = 0;
|
|
475
|
+
const set = /* @__PURE__ */ new Set();
|
|
476
|
+
for (let i = 0; i < item.flatCronGroups.length; i++) {
|
|
477
|
+
const job = item.flatCronGroups[i];
|
|
478
|
+
if (job.group === 0 && matches(job.cron, now)) {
|
|
479
|
+
count++;
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
if (!set.has(job.group) && matches(job.cron, now)) {
|
|
483
|
+
count++;
|
|
484
|
+
set.add(job.group);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return {
|
|
488
|
+
filepath: item.filepath,
|
|
489
|
+
interpreter: item.interpreter,
|
|
490
|
+
count
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* 判断文件本轮是否该运行
|
|
495
|
+
*
|
|
496
|
+
* @param cx Cronjob 上下文
|
|
497
|
+
* @param files 文件内容数组
|
|
498
|
+
* @param now 当前时间,**秒数、毫秒数为0**
|
|
499
|
+
* @returns 要跑的 cron,要跑多少次;
|
|
500
|
+
*/
|
|
501
|
+
function getJobs(cx, files, now) {
|
|
502
|
+
const jobs = [];
|
|
503
|
+
for (let i = 0; i < files.length; i++) {
|
|
504
|
+
const f = files[i];
|
|
505
|
+
if (f.error) {
|
|
506
|
+
cx.log.err(`Error loading file ${path.relative(cx.dir, f.filepath)}: ${f.error}`);
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
if (f.content === null) continue;
|
|
510
|
+
const jobItem = getJobItem(cx, f.filepath, f.content);
|
|
511
|
+
if (!jobItem) continue;
|
|
512
|
+
const job = getMatchedJob(cx, jobItem, now);
|
|
513
|
+
if (job.count > 0) jobs.push(job);
|
|
514
|
+
}
|
|
515
|
+
return jobs;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// src/initialize.ts
|
|
519
|
+
/**
|
|
520
|
+
* 检查 tsx 是否可用;没有只警告,纯 js/sh 任务仍可运行
|
|
521
|
+
*/
|
|
522
|
+
const orTsx = (cx) => {
|
|
523
|
+
if (!cx.runtime.hasTsx) cx.log.warn(`'tsx' not found, .ts files will be run by node directly. Not all nodejs versions supports this.`);
|
|
524
|
+
};
|
|
525
|
+
const orPython = (cx) => {
|
|
526
|
+
if (cx.runtime.pythonCmd !== "none") cx.log.info(`python available, .py files will be run by ${cx.runtime.pythonCmd}`);
|
|
527
|
+
else cx.log.warn("python not available, .py jobs will be ignored");
|
|
528
|
+
};
|
|
529
|
+
const ensureDir = (cx) => {
|
|
530
|
+
mkdirSync(cx.dir, {
|
|
531
|
+
recursive: true,
|
|
532
|
+
mode: 493
|
|
533
|
+
});
|
|
534
|
+
if (cx.dir !== cx.logDir) mkdirSync(cx.logDir, {
|
|
535
|
+
recursive: true,
|
|
536
|
+
mode: 493
|
|
537
|
+
});
|
|
538
|
+
};
|
|
539
|
+
/**
|
|
540
|
+
* dir / logDir 必须只有 runner 用户能写。
|
|
541
|
+
* - dir 可写 = 能以 runner 的身份执行任意代码;logDir 可写 = 能往任务日志里追加内容
|
|
542
|
+
* - 属主不是当前用户、或 group/other 有写位,都直接报错(不是告警)
|
|
543
|
+
* - root 除外:root 能写任何目录,这条检查对 root 没有意义
|
|
544
|
+
*/
|
|
545
|
+
const checkDirPermissions = (cx) => {
|
|
546
|
+
if (typeof process.getuid !== "function" || process.getuid() === 0) return;
|
|
547
|
+
for (const [name, dir] of [["dir", cx.dir], ["logDir", cx.logDir]]) {
|
|
548
|
+
const { mode, uid } = statSync(dir);
|
|
549
|
+
const writableByOthers = (mode & 18) !== 0;
|
|
550
|
+
if (uid !== process.getuid() || writableByOthers) throw new Error(`${name} must be owned by the current user and not group/world-writable: ${dir} (owner=${uid}, mode=${(mode & 511).toString(8)})`);
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
/**
|
|
554
|
+
* 锁名用的目录标识:realpath 兜住符号链接(/a/link 与 /b/real 是同一个目录时也能识别),
|
|
555
|
+
* 目录还不存在时退回 resolve 的结果(ensureDir 在拿锁之后才建目录)。
|
|
556
|
+
*/
|
|
557
|
+
const lockKeyOf = (dir) => {
|
|
558
|
+
try {
|
|
559
|
+
return realpathSync(dir);
|
|
560
|
+
} catch {
|
|
561
|
+
return resolve(dir);
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
/**
|
|
565
|
+
* 绑定成功则 resolve(进程活着就一直占着);
|
|
566
|
+
* 已被占用则 reject —— 不 process.exit,由宿主决定怎么退。
|
|
567
|
+
* @returns {Promise<void>}
|
|
568
|
+
*/
|
|
569
|
+
const acquireLock = (cx) => new Promise((resolve, reject) => {
|
|
570
|
+
/**
|
|
571
|
+
* 锁名跟着任务目录走,同一台机器跑多个项目时不会互相误伤。
|
|
572
|
+
* \0 前缀 = 抽象 namespace,不落盘;进程退出(含 kill -9)由内核自动释放。
|
|
573
|
+
* exclusive: true —— cluster 模式下 listen 默认交给 primary 代绑并共享句柄,
|
|
574
|
+
* 每个 worker 都会"成功",锁就失效了;exclusive 让每个 worker 自己真绑,第二个拿到 EADDRINUSE。
|
|
575
|
+
*/
|
|
576
|
+
const LOCK_NAME = "\0krontab-" + createHash("sha1").update(lockKeyOf(cx.dir)).digest("hex").slice(0, 8);
|
|
577
|
+
const server = net.createServer();
|
|
578
|
+
server.once("error", (e) => {
|
|
579
|
+
reject(e.code === "EADDRINUSE" ? /* @__PURE__ */ new Error("krontab already running") : e);
|
|
580
|
+
});
|
|
581
|
+
server.listen({
|
|
582
|
+
path: LOCK_NAME,
|
|
583
|
+
exclusive: true
|
|
584
|
+
}, () => {
|
|
585
|
+
server.unref();
|
|
586
|
+
resolve();
|
|
587
|
+
});
|
|
588
|
+
});
|
|
589
|
+
const initialize = async (cx) => {
|
|
590
|
+
await acquireLock(cx);
|
|
591
|
+
ensureDir(cx);
|
|
592
|
+
checkDirPermissions(cx);
|
|
593
|
+
orTsx(cx);
|
|
594
|
+
orPython(cx);
|
|
595
|
+
};
|
|
596
|
+
|
|
597
|
+
// src/run.ts
|
|
598
|
+
function run(cx, { filepath, interpreter }) {
|
|
599
|
+
let output = null;
|
|
600
|
+
const closeOutput = () => {
|
|
601
|
+
if (output !== null) {
|
|
602
|
+
fs.closeSync(output);
|
|
603
|
+
output = null;
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
const relativePath = path.relative(cx.dir, filepath);
|
|
607
|
+
try {
|
|
608
|
+
const logfile = path.join(cx.logDir, relativePath + ".log");
|
|
609
|
+
fs.mkdirSync(path.dirname(logfile), { recursive: true });
|
|
610
|
+
if (interpreter.cmd === "none") {
|
|
611
|
+
cx.log.warn(`path=${relativePath} unsupported extension`);
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
const cmd = interpreter.cmd;
|
|
615
|
+
const args = interpreter.args.concat(filepath);
|
|
616
|
+
output = fs.openSync(logfile, "a", 416);
|
|
617
|
+
const child = spawn(cmd, args, {
|
|
618
|
+
stdio: [
|
|
619
|
+
"ignore",
|
|
620
|
+
output,
|
|
621
|
+
output
|
|
622
|
+
],
|
|
623
|
+
detached: true,
|
|
624
|
+
env,
|
|
625
|
+
cwd: cx.jobcwd(filepath)
|
|
626
|
+
});
|
|
627
|
+
child.on("error", (e) => {
|
|
628
|
+
closeOutput();
|
|
629
|
+
cx.log.err(`path=${relativePath} pid=${child.pid ?? "-1"}`, e);
|
|
630
|
+
});
|
|
631
|
+
child.on("spawn", () => {
|
|
632
|
+
closeOutput();
|
|
633
|
+
cx.log.spawn(`path=${relativePath} pid=${child.pid ?? "-1"}`);
|
|
634
|
+
});
|
|
635
|
+
child.on("exit", (code, signal) => {
|
|
636
|
+
closeOutput();
|
|
637
|
+
cx.log.exit(`path=${relativePath} pid=${child.pid ?? "-1"} code=${code} signal=${signal}`);
|
|
638
|
+
});
|
|
639
|
+
child.unref();
|
|
640
|
+
} catch (e) {
|
|
641
|
+
closeOutput();
|
|
642
|
+
cx.log.err(`path=${relativePath} pid=-1`, e);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// src/list.ts
|
|
647
|
+
/**
|
|
648
|
+
* 罗列所有定时表达式,效果类似 `crontab -l`
|
|
649
|
+
*
|
|
650
|
+
* 输出四列:下次运行时间、表达式、相对路径、解释器命令
|
|
651
|
+
* - 块内的多条表达式会缩进显示,并标出 group
|
|
652
|
+
* - 同一条表达式每次都重新 parse,避免 next() 改动共享对象的内部游标
|
|
653
|
+
*/
|
|
654
|
+
async function list(cx) {
|
|
655
|
+
const filepaths = tryGlobSync(cx);
|
|
656
|
+
if (!filepaths) return;
|
|
657
|
+
if (filepaths.length === 0) {
|
|
658
|
+
cx.log.info(`No scripts found in ${cx.dir}`);
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
const files = await loadFiles(cx, filepaths);
|
|
662
|
+
for (const f of files) {
|
|
663
|
+
const relativePath = path.relative(cx.dir, f.filepath);
|
|
664
|
+
if (f.error) {
|
|
665
|
+
cx.log.err(`Error loading file ${relativePath}: ${f.error}`);
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
if (f.content === null) continue;
|
|
669
|
+
const item = getJobItem(cx, f.filepath, f.content);
|
|
670
|
+
if (!item) continue;
|
|
671
|
+
if (item.flatCronGroups.length === 0) {
|
|
672
|
+
cx.log.warn(`No cron expression: ${relativePath}`);
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
const invocation = [
|
|
676
|
+
item.interpreter.cmd,
|
|
677
|
+
...item.interpreter.args,
|
|
678
|
+
relativePath
|
|
679
|
+
].join(" ");
|
|
680
|
+
for (const { cron, group, timezone } of item.flatCronGroups) {
|
|
681
|
+
const exp = cron.stringify();
|
|
682
|
+
const next = nextRunText(cx, exp, f.filepath, timezone);
|
|
683
|
+
const prefix = (group > 0 ? ` [${group}] ` : "") + (timezone === "UTC" ? "UTC " : "");
|
|
684
|
+
console.log(`${next.padEnd(24)} ${(prefix + exp).padEnd(18)} ${relativePath.padEnd(32)} ${invocation}`);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
/** 表达式在上一次 parse 后可能因 impossible date 抛错,这里只展示、不中断整个列表 */
|
|
689
|
+
function nextRunText(cx, exp, filepath, timezone) {
|
|
690
|
+
const parsed = parseExp(cx, exp, filepath, timezone);
|
|
691
|
+
if (!parsed) return "(invalid)";
|
|
692
|
+
try {
|
|
693
|
+
return cx.timeFormat.format(parsed.next().toDate());
|
|
694
|
+
} catch {
|
|
695
|
+
return "(no next run)";
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// src/index.ts
|
|
700
|
+
/**
|
|
701
|
+
* 启动定时任务主理,返回控制器
|
|
702
|
+
* - 只支持 5 段 cron:分 时 日 月 周
|
|
703
|
+
* - 同一 dir 只允许一个实例
|
|
704
|
+
*/
|
|
705
|
+
async function cronjob(config) {
|
|
706
|
+
const cx = createContext(config);
|
|
707
|
+
cx.log.info(`Config loaded: ${JSON.stringify(cx)}`);
|
|
708
|
+
if (process.argv.includes("--list") || process.argv.includes("-l")) {
|
|
709
|
+
await list(cx);
|
|
710
|
+
process.exit(0);
|
|
711
|
+
}
|
|
712
|
+
await initialize(cx);
|
|
713
|
+
const taskFn = async (now) => {
|
|
714
|
+
const filepaths = tryGlobSync(cx);
|
|
715
|
+
if (!filepaths) return;
|
|
716
|
+
if (filepaths.length === 0) {
|
|
717
|
+
cx.log.info(`No scripts found.`);
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
const performanceNow = performance.now();
|
|
721
|
+
cx.log.debug(`Start`);
|
|
722
|
+
const files = await loadFiles(cx, filepaths);
|
|
723
|
+
const jobs = await getJobs(cx, files, now);
|
|
724
|
+
if (cx.jobState === 2) return;
|
|
725
|
+
for (let i = 0; i < jobs.length; i++) for (let n = 0; n < jobs[i].count; n++) if (cx.jobState === 0) run(cx, jobs[i]);
|
|
726
|
+
cx.log.debug(`Finished in ${(performance.now() - performanceNow).toFixed(6)}ms`);
|
|
727
|
+
};
|
|
728
|
+
const task = runTask(cx, taskFn);
|
|
729
|
+
cx.log.info(`Cronjob start! pid=${process.pid}`);
|
|
730
|
+
return task;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
export { cronjob };
|
|
8
734
|
//# sourceMappingURL=index.mjs.map
|