feat(cron): expose run receipts and modularize execution

Return committed trigger IDs and add CLI wait and trigger-specific logs while
preserving API, CLI, transaction, deduplication and unknown-result semantics.

Move scheduling, lifecycle, settlement, queries and legacy adapters into
back/cron; remove obsolete internal import paths and circular dependencies.

Apply project formatting across the repository, cover CJS/MJS in formatting
hooks, add prettier:check and require formatting checks in AGENTS.md.

Validation: backend build; 1398 backend/frontend tests passed (17 platform
skips); 327 CLI tests passed (6 platform skips); 670 files pass format checks.
This commit is contained in:
whyour committed 2026-11-22 12:24:29 +08:00
1 parent 77ece406ac
commit c5458596c8
346 files changed
+32133 -11556

No files matched your search

+6 -2
View File
@@ -97,9 +97,13 @@ export default (app: Router) => {
}
// OpenAPI config scopes grant data-file access, not executable hooks.
if (/(?:^|\/)open\/configs(?:\/|\?|$)/.test(req.originalUrl || '')) {
const realPath = await fs.realpath(normalized).catch(() => normalized);
const realPath = await fs
.realpath(normalized)
.catch(() => normalized);
if (
openApiProtectedFiles.has(path.basename(normalized).toLowerCase()) ||
openApiProtectedFiles.has(
path.basename(normalized).toLowerCase(),
) ||
openApiProtectedFiles.has(path.basename(realPath).toLowerCase())
) {
return res.send({ code: 403, message: t('文件无法访问') });
+208 -83
View File
@@ -1,8 +1,12 @@
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
import { readDailyResults } from '../shared/legacyDailyStatistics';
import {
executionIdPattern,
executionTriggerId,
receiptFinishTime,
} from '../cron/identity';
import { readDailyResults } from '../cron/settlement/legacyDailyStatistics';
import { PendingCronInstall } from '../shared/errors';
import { triggerHistory } from '../shared/triggerHistory';
import { previewSchedule, withNextRun } from '../shared/cronPreview';
import { triggerHistory } from '../cron/history';
import { previewSchedule, withNextRun } from '../cron/queries/cronPreview';
import { Router, Request, Response, NextFunction } from 'express';
import { literal, Op } from 'sequelize';
import { Container } from 'typedi';
@@ -11,10 +15,7 @@ import CronService from '../services/cron';
import CronViewService from '../services/cronView';
import { celebrate, Joi } from 'celebrate';
import { commonCronSchema } from '../validation/schedule';
import {
RunningInstanceModel,
InstanceStatus,
} from '../data/runningInstance';
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
import { t } from '../shared/i18n';
import cronClient from '../schedule/client';
@@ -25,8 +26,17 @@ export default (app: Router) => {
route.use(async (req, res, next) => {
// Keep stop/status callbacks available even when the scheduler is down.
if (['POST', 'PUT', 'DELETE'].includes(req.method) &&
['/', '/run', '/enable', '/disable', '/views/enable', '/views/disable'].includes(req.path)) {
if (
['POST', 'PUT', 'DELETE'].includes(req.method) &&
[
'/',
'/run',
'/enable',
'/disable',
'/views/enable',
'/views/disable',
].includes(req.path)
) {
try {
await cronClient.readiness.ensureReady();
} catch (error) {
@@ -171,23 +181,44 @@ export default (app: Router) => {
try {
const cronService = Container.get(CronService);
const result = await cronService.crontabs(req.query as any, true);
return res.send({ code: 200, data: { ...result, data: result.data.map(withNextRun) } });
return res.send({
code: 200,
data: { ...result, data: result.data.map(withNextRun) },
});
} catch (e) {
logger.error('🔥 error: %o', e);
return next(e);
}
});
route.get('/preview', celebrate({ query: Joi.object({
schedule: Joi.string().required(),
}).unknown(true) }), (req, res) => {
try {
const times = previewSchedule(String(req.query.schedule), 3, Date.now());
return res.send({ code: 200, data: { times, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone } });
} catch {
return res.status(400).send({ code: 400, message: t('Cron表达式格式有误') });
}
});
route.get(
'/preview',
celebrate({
query: Joi.object({
schedule: Joi.string().required(),
}).unknown(true),
}),
(req, res) => {
try {
const times = previewSchedule(
String(req.query.schedule),
3,
Date.now(),
);
return res.send({
code: 200,
data: {
times,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
},
});
} catch {
return res
.status(400)
.send({ code: 400, message: t('Cron表达式格式有误') });
}
},
);
route.get(
'/detail',
@@ -218,7 +249,9 @@ export default (app: Router) => {
} catch (e) {
if (e instanceof PendingCronInstall) {
return res.status(e.status).send({
code: e.status, message: e.message, data: { id: e.cronId, saved: false },
code: e.status,
message: e.message,
data: { id: e.cronId, saved: false },
});
}
return next(e);
@@ -246,14 +279,19 @@ export default (app: Router) => {
route.put(
'/stop',
celebrate({
headers: Joi.object({ 'idempotency-key': Joi.string().guid().optional() }).unknown(true),
headers: Joi.object({
'idempotency-key': Joi.string().guid().optional(),
}).unknown(true),
body: Joi.array().items(Joi.number().required()),
}),
async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
try {
const cronService = Container.get(CronService);
const data = await cronService.stop(req.body, req.get('Idempotency-Key'));
const data = await cronService.stop(
req.body,
req.get('Idempotency-Key'),
);
return res.send({ code: 200, data });
} catch (e) {
return next(e);
@@ -349,7 +387,9 @@ export default (app: Router) => {
instanceId: Joi.number().integer().positive().optional(),
previousPath: Joi.string().optional(),
follow: Joi.boolean().optional(),
cursor: Joi.string().pattern(/^\d{1,16}\.[a-f0-9]{64}$/).optional(),
cursor: Joi.string()
.pattern(/^\d{1,16}\.[a-f0-9]{64}$/)
.optional(),
offset: Joi.number().integer().min(0).optional(),
limit: Joi.number()
.integer()
@@ -366,7 +406,10 @@ export default (app: Router) => {
const cronService = Container.get(CronService);
const result = await cronService.log(req.params.id, {
triggerId: req.query.triggerId as string | undefined,
instanceId: req.query.instanceId === undefined ? undefined : Number(req.query.instanceId),
instanceId:
req.query.instanceId === undefined
? undefined
: Number(req.query.instanceId),
previousPath: req.query.previousPath as string | undefined,
follow: req.query.follow as unknown as boolean,
cursor: req.query.cursor as string | undefined,
@@ -416,10 +459,18 @@ export default (app: Router) => {
route.delete(
'/',
celebrate({
body: Joi.array().min(1).items(Joi.number().integer().positive(), Joi.object({
id: Joi.number().integer().positive().required(), script: Joi.string().required(),
revision: Joi.number().integer(), command: Joi.string(), sub_id: Joi.number().integer().allow(null),
})),
body: Joi.array()
.min(1)
.items(
Joi.number().integer().positive(),
Joi.object({
id: Joi.number().integer().positive().required(),
script: Joi.string().required(),
revision: Joi.number().integer(),
command: Joi.string(),
sub_id: Joi.number().integer().allow(null),
}),
),
}),
async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
@@ -513,7 +564,9 @@ export default (app: Router) => {
exit_code: Joi.number().optional().allow(null),
trigger_stopped: Joi.boolean().optional(),
execution_id: Joi.string().pattern(executionIdPattern).optional(),
trigger_id: Joi.string().pattern(/^[a-z0-9-]{1,120}$/).optional(),
trigger_id: Joi.string()
.pattern(/^[a-z0-9-]{1,120}$/)
.optional(),
}).oxor('execution_id', 'trigger_id'),
}),
async (req: Request, res: Response, next: NextFunction) => {
@@ -534,56 +587,100 @@ export default (app: Router) => {
},
);
route.get('/:id/daily-results', celebrate({
params: Joi.object({ id: Joi.number().integer().positive().required() }),
}), async (req, res, next) => {
try {
const data = await readDailyResults(RunningInstanceModel.sequelize!, Number(req.params.id));
return res.send({ code: 200, data });
} catch (error) {
return next(error);
}
});
route.get('/:id/triggers', celebrate({
params: Joi.object({ id: Joi.number().integer().positive().required() }),
query: Joi.object({
offset: Joi.number().integer().min(0),
limit: Joi.number().integer().min(1).max(26).default(25),
ids: Joi.array().items(Joi.string().max(256)).min(1).max(25).single(),
beforeTime: Joi.number().integer().min(0),
beforeId: Joi.string().max(256),
}).and('beforeTime', 'beforeId').oxor('offset', 'beforeTime', 'ids').unknown(true),
}), async (req, res, next) => {
try {
const { offset, limit, beforeTime, beforeId, ids } = req.query;
const history = triggerHistory();
const before = beforeId ? { time: Number(beforeTime), id: String(beforeId) } : undefined;
const data = ids
? await history.visibleTriggers(Number(req.params.id), ids as string[])
: await history.recent(Number(req.params.id), Number(offset || 0), Number(limit), before);
if (req.query.withQueueWait === 'true') {
const now = Date.now();
return res.send({ code: 200, data: data.map(row => row.state === 'queued' && row.queued_at != null
? { ...row, queue_wait_ms: Math.max(0, (row.dequeued_at ?? now) - row.queued_at) } : row) });
route.get(
'/:id/daily-results',
celebrate({
params: Joi.object({ id: Joi.number().integer().positive().required() }),
}),
async (req, res, next) => {
try {
const data = await readDailyResults(
RunningInstanceModel.sequelize!,
Number(req.params.id),
);
return res.send({ code: 200, data });
} catch (error) {
return next(error);
}
return res.send({ code: 200, data });
} catch (err) { next(err); }
});
},
);
route.get(
'/:id/triggers',
celebrate({
params: Joi.object({ id: Joi.number().integer().positive().required() }),
query: Joi.object({
offset: Joi.number().integer().min(0),
limit: Joi.number().integer().min(1).max(26).default(25),
ids: Joi.array().items(Joi.string().max(256)).min(1).max(25).single(),
beforeTime: Joi.number().integer().min(0),
beforeId: Joi.string().max(256),
})
.and('beforeTime', 'beforeId')
.oxor('offset', 'beforeTime', 'ids')
.unknown(true),
}),
async (req, res, next) => {
try {
const { offset, limit, beforeTime, beforeId, ids } = req.query;
const history = triggerHistory();
const before = beforeId
? { time: Number(beforeTime), id: String(beforeId) }
: undefined;
const data = ids
? await history.visibleTriggers(
Number(req.params.id),
ids as string[],
)
: await history.recent(
Number(req.params.id),
Number(offset || 0),
Number(limit),
before,
);
if (req.query.withQueueWait === 'true') {
const now = Date.now();
return res.send({
code: 200,
data: data.map((row) =>
row.state === 'queued' && row.queued_at != null
? {
...row,
queue_wait_ms: Math.max(
0,
(row.dequeued_at ?? now) - row.queued_at,
),
}
: row,
),
});
}
return res.send({ code: 200, data });
} catch (err) {
next(err);
}
},
);
route.get(
'/:id/instances',
celebrate({
// This route historically ignored query parameters. Only validate and
// apply cursor options when the caller explicitly requests pagination.
query: Joi.alternatives().conditional(Joi.object({ paged: Joi.valid('true').required() }).unknown(), {
then: Joi.object({
limit: Joi.number().integer().min(1).max(100),
before: Joi.number().integer().positive(),
ids: Joi.string().pattern(/^\d+(,\d+){0,99}$/),
}).unknown(true).oxor('ids', 'limit').oxor('ids', 'before'),
otherwise: Joi.object().unknown(true),
}),
query: Joi.alternatives().conditional(
Joi.object({ paged: Joi.valid('true').required() }).unknown(),
{
then: Joi.object({
limit: Joi.number().integer().min(1).max(100),
before: Joi.number().integer().positive(),
ids: Joi.string().pattern(/^\d+(,\d+){0,99}$/),
})
.unknown(true)
.oxor('ids', 'limit')
.oxor('ids', 'before'),
otherwise: Joi.object().unknown(true),
},
),
params: Joi.object({
id: Joi.number().required(),
}),
@@ -594,27 +691,48 @@ export default (app: Router) => {
const pending = `EXISTS (SELECT 1 FROM CronTriggers t WHERE t.instance_id=RunningInstance.id
AND (t.exit_pending=1 OR (t.state='unknown' AND t.reason='restart')))`;
const paged = req.query.paged === 'true';
const ids = paged && req.query.ids ? String(req.query.ids).split(',').map(Number) : undefined;
const ids =
paged && req.query.ids
? String(req.query.ids).split(',').map(Number)
: undefined;
const limit = paged && !ids ? Number(req.query.limit ?? 25) : undefined;
const instances = await RunningInstanceModel.findAll({
attributes: {
exclude: ['finished_at', 'exit_code'],
include: [
[literal(`CASE WHEN ${pending} THEN NULL ELSE finished_at END`), 'finished_at'],
[literal(`CASE WHEN ${pending} THEN NULL ELSE exit_code END`), 'exit_code'],
[
literal(`CASE WHEN ${pending} THEN NULL ELSE finished_at END`),
'finished_at',
],
[
literal(`CASE WHEN ${pending} THEN NULL ELSE exit_code END`),
'exit_code',
],
],
},
where: {
cron_id: req.params.id,
...(ids && { id: { [Op.in]: ids } }),
...(paged && req.query.before && { id: { [Op.lt]: Number(req.query.before) } }),
...(paged &&
req.query.before && {
id: { [Op.lt]: Number(req.query.before) },
}),
},
order: paged ? [['id', 'DESC']] : [['started_at', 'DESC'], ['id', 'DESC']],
order: paged
? [['id', 'DESC']]
: [
['started_at', 'DESC'],
['id', 'DESC'],
],
...(limit && { limit: limit + 1 }),
raw: true,
});
if (limit) return res.send({ code: 200, data: instances.slice(0, limit),
next: instances.length > limit ? instances[limit - 1].id : null });
if (limit)
return res.send({
code: 200,
data: instances.slice(0, limit),
next: instances.length > limit ? instances[limit - 1].id : null,
});
return res.send({ code: 200, data: instances });
} catch (e) {
return next(e);
@@ -630,10 +748,17 @@ export default (app: Router) => {
instanceId: Joi.number().required(),
}),
}),
async (req: Request<{ id: number; instanceId: number }>, res: Response, next: NextFunction) => {
async (
req: Request<{ id: number; instanceId: number }>,
res: Response,
next: NextFunction,
) => {
try {
const cronService = Container.get(CronService);
const data = await cronService.stopInstance(Number(req.params.id), Number(req.params.instanceId));
const data = await cronService.stopInstance(
Number(req.params.id),
Number(req.params.instanceId),
);
return res.status(data.code).send(data);
} catch (e) {
return next(e);
+241 -97
View File
@@ -1,23 +1,24 @@
import config from '../config';
import { stat } from 'fs/promises';
import { resolveFileAccess } from '../shared/fileAccess';
import { AnomalyPage, AnomalyKind } from '../shared/scheduleAnomalies';
import { auditSchedule } from '../shared/scheduleAudit';
import { systemScheduleAudit } from '../shared/systemScheduleAudit';
import { AnomalyPage, AnomalyKind } from '../cron/queries/scheduleAnomalies';
import { auditSchedule } from '../cron/scheduling/scheduleAudit';
import { systemScheduleAudit } from '../cron/scheduling/systemScheduleAudit';
import { celebrate, Joi } from 'celebrate';
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
import { oldestQueued } from '../shared/queueDiagnostics';
import {
executionIdPattern,
executionTriggerId,
receiptFinishTime,
} from '../cron/identity';
import { oldestQueued } from '../cron/queries/queueDiagnostics';
import { containerResources } from '../shared/containerResources';
import { TriggerHistory } from '../shared/triggerHistory';
import { TriggerHistory } from '../cron/history';
import { Router, Request, Response, NextFunction } from 'express';
import { Container } from 'typedi';
import { fn, col, where, Op, QueryTypes } from 'sequelize';
import { CrontabModel } from '../data/cron';
import { CrontabStatModel } from '../data/cronStats';
import {
RunningInstanceModel,
InstanceStatus,
} from '../data/runningInstance';
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
import dayjs from 'dayjs';
import os from 'os';
import { isEmpty } from 'lodash';
@@ -38,21 +39,49 @@ export default (app: Router) => {
const { ref_id, code, elapsed, trigger_id, execution_id } = req.body;
if (!ref_id) return res.send({ code: 400, message: 'ref_id required' });
if (trigger_id != null && (typeof trigger_id !== 'string' || !/^[a-z0-9-]{1,120}$/.test(trigger_id))) {
if (
trigger_id != null &&
(typeof trigger_id !== 'string' ||
!/^[a-z0-9-]{1,120}$/.test(trigger_id))
) {
return res.send({ code: 400 });
}
if (execution_id !== undefined && (trigger_id !== undefined ||
typeof execution_id !== 'string' || !executionIdPattern.test(execution_id))) return res.send({ code: 400 });
if (
execution_id !== undefined &&
(trigger_id !== undefined ||
typeof execution_id !== 'string' ||
!executionIdPattern.test(execution_id))
)
return res.send({ code: 400 });
const id = execution_id ? executionTriggerId(execution_id) : trigger_id;
// Old wrappers also send a status receipt with the process identity.
// A stats-only retry cannot be distinguished from another identical run.
if (!id) return res.send({ code: 200, data: { counted: false, reason: 'missing_execution_identity' } });
const exitCode = typeof code === 'string' && /^-?\d+$/.test(code) ? Number(code) : code;
if (!id)
return res.send({
code: 200,
data: { counted: false, reason: 'missing_execution_identity' },
});
const exitCode =
typeof code === 'string' && /^-?\d+$/.test(code) ? Number(code) : code;
const elapsedMs = Number(elapsed ?? 0) * 1000;
if (!Number.isInteger(exitCode) || !Number.isSafeInteger(elapsedMs) || elapsedMs < 0) {
return res.send({ code: 400, message: 'invalid exit code or elapsed time' });
if (
!Number.isInteger(exitCode) ||
!Number.isSafeInteger(elapsedMs) ||
elapsedMs < 0
) {
return res.send({
code: 400,
message: 'invalid exit code or elapsed time',
});
}
await new TriggerHistory(CrontabStatModel.sequelize!).recordShellResult(id, Number(ref_id), exitCode, elapsedMs, Date.now(), receiptFinishTime(req.get('X-QL-Finished-At')));
await new TriggerHistory(CrontabStatModel.sequelize!).recordShellResult(
id,
Number(ref_id),
exitCode,
elapsedMs,
Date.now(),
receiptFinishTime(req.get('X-QL-Finished-At')),
);
res.send({ code: 200 });
} catch (e) {
res.send({ code: 500 });
@@ -82,7 +111,9 @@ export default (app: Router) => {
where: { date: today },
raw: true,
}),
new TriggerHistory(CrontabStatModel.sequelize!).metrics(day.valueOf()),
new TriggerHistory(CrontabStatModel.sequelize!).metrics(
day.valueOf(),
),
]);
const row = stats as any;
@@ -104,8 +135,11 @@ export default (app: Router) => {
todaySuccess: totalSuccess,
todayFail: totalFail,
todayStopped: totalRuns - totalSuccess - totalFail,
successRate: totalRuns > 0 ? ((totalSuccess / totalRuns) * 100).toFixed(1) : '0',
avgTime: averageElapsed(totalTime,totalRuns,row?.untimed_count),
successRate:
totalRuns > 0
? ((totalSuccess / totalRuns) * 100).toFixed(1)
: '0',
avgTime: averageElapsed(totalTime, totalRuns, row?.untimed_count),
},
});
} catch (e) {
@@ -114,55 +148,115 @@ export default (app: Router) => {
},
);
route.get('/schedule-anomalies', celebrate({ query: Joi.object({
source: Joi.string().valid('panel', 'system').required(),
kind: Joi.string().valid('missing', 'skipped', 'unconfirmed').required(),
at: Joi.number().integer().positive().required(),
page: Joi.number().integer().min(1).default(1),
revision: Joi.string().hex().length(64),
live: Joi.boolean().default(false),
}).unknown(true) }), async (req, res, next) => {
try {
const { source, kind, page, at, revision, live } = req.query;
const until = Number(at);
const serverNow = Date.now();
const expiresAt = dayjs(until).startOf('day').add(1, 'day').valueOf();
if (live && serverNow >= expiresAt)
return res.send({ code: 200, data: { status: 'expired' } });
if (until > Date.now() || until < dayjs().subtract(1, 'day').startOf('day').valueOf())
return res.status(400).send({ code: 400 });
const [snapshotRetention] = live ? await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
'SELECT cutoff FROM CronHistoryRetention WHERE id=1', { type: QueryTypes.SELECT },
) : [];
const details = new AnomalyPage(kind as AnomalyKind, Number(page), revision as string | undefined);
const audit = source === 'panel' ? auditSchedule : systemScheduleAudit;
const summary = await audit(CrontabStatModel.sequelize!, dayjs(until).startOf('day').valueOf(), until, details);
if (live && (!summary || summary.since > summary.through))
return res.send({ code: 200, data: { status: 'unavailable' } });
if (!summary) return res.status(409).send({ code: 409 });
const result = details.result();
const ids = [...new Set(result.rows.filter(row => !row.name).map(row => row.task))];
const tasks = ids.length ? await CrontabModel.findAll({ where: { id: ids }, attributes: ['id','name','command'], raw: true }) : [];
const names = new Map(tasks.map(task => [task.id, task.name || task.command]));
const rows = await Promise.all(result.rows.map(async ({ logPath, ...row }) => {
const path = logPath && resolveFileAccess(config.logPath, [logPath]);
const hasLog = path ? await stat(path).then(file => file.isFile(), () => false) : false;
return { ...row, name: row.name || names.get(row.task), hasLog };
}));
// Log checks can yield after the audit transaction. Do not publish that
// snapshot if history cleanup has since removed part of its plan window.
if (live) {
const [retention] = await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
'SELECT cutoff FROM CronHistoryRetention WHERE id=1', { type: QueryTypes.SELECT },
route.get(
'/schedule-anomalies',
celebrate({
query: Joi.object({
source: Joi.string().valid('panel', 'system').required(),
kind: Joi.string()
.valid('missing', 'skipped', 'unconfirmed')
.required(),
at: Joi.number().integer().positive().required(),
page: Joi.number().integer().min(1).default(1),
revision: Joi.string().hex().length(64),
live: Joi.boolean().default(false),
}).unknown(true),
}),
async (req, res, next) => {
try {
const { source, kind, page, at, revision, live } = req.query;
const until = Number(at);
const serverNow = Date.now();
const expiresAt = dayjs(until).startOf('day').add(1, 'day').valueOf();
if (live && serverNow >= expiresAt)
return res.send({ code: 200, data: { status: 'expired' } });
if (
until > Date.now() ||
until < dayjs().subtract(1, 'day').startOf('day').valueOf()
)
return res.status(400).send({ code: 400 });
const [snapshotRetention] = live
? await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
'SELECT cutoff FROM CronHistoryRetention WHERE id=1',
{ type: QueryTypes.SELECT },
)
: [];
const details = new AnomalyPage(
kind as AnomalyKind,
Number(page),
revision as string | undefined,
);
if (retention && retention.cutoff > (snapshotRetention?.cutoff ?? 0))
const audit = source === 'panel' ? auditSchedule : systemScheduleAudit;
const summary = await audit(
CrontabStatModel.sequelize!,
dayjs(until).startOf('day').valueOf(),
until,
details,
);
if (live && (!summary || summary.since > summary.through))
return res.send({ code: 200, data: { status: 'unavailable' } });
if (!summary) return res.status(409).send({ code: 409 });
const result = details.result();
const ids = [
...new Set(
result.rows.filter((row) => !row.name).map((row) => row.task),
),
];
const tasks = ids.length
? await CrontabModel.findAll({
where: { id: ids },
attributes: ['id', 'name', 'command'],
raw: true,
})
: [];
const names = new Map(
tasks.map((task) => [task.id, task.name || task.command]),
);
const rows = await Promise.all(
result.rows.map(async ({ logPath, ...row }) => {
const path =
logPath && resolveFileAccess(config.logPath, [logPath]);
const hasLog = path
? await stat(path).then(
(file) => file.isFile(),
() => false,
)
: false;
return { ...row, name: row.name || names.get(row.task), hasLog };
}),
);
// Log checks can yield after the audit transaction. Do not publish that
// snapshot if history cleanup has since removed part of its plan window.
if (live) {
const [retention] = await CrontabStatModel.sequelize!.query<{
cutoff: number;
}>('SELECT cutoff FROM CronHistoryRetention WHERE id=1', {
type: QueryTypes.SELECT,
});
if (retention && retention.cutoff > (snapshotRetention?.cutoff ?? 0))
return res.send({ code: 200, data: { status: 'unavailable' } });
}
if (live && Date.now() >= expiresAt)
return res.send({ code: 200, data: { status: 'expired' } });
return res.send({
code: 200,
data: {
...result,
rows,
serverNow,
expiresAt,
summary:
source === 'panel'
? { audit: summary }
: { systemAudit: summary },
zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
},
});
} catch (error) {
next(error);
}
if (live && Date.now() >= expiresAt)
return res.send({ code: 200, data: { status: 'expired' } });
return res.send({ code: 200, data: { ...result, rows, serverNow, expiresAt, summary: source === 'panel' ? { audit: summary } : { systemAudit: summary }, zone: Intl.DateTimeFormat().resolvedOptions().timeZone } });
} catch (error) { next(error); }
});
},
);
for (const isSuccess of [false, true]) {
route.get(
@@ -171,17 +265,31 @@ export default (app: Router) => {
try {
const countColumn = isSuccess ? 'success_count' : 'fail_count';
const rows = (await CrontabStatModel.findAll({
attributes: ['ref_id', [fn('SUM', col(countColumn)), 'result_count']],
where: { date: dayjs().format('YYYY-MM-DD'), [countColumn]: { [Op.gt]: 0 } },
attributes: [
'ref_id',
[fn('SUM', col(countColumn)), 'result_count'],
],
where: {
date: dayjs().format('YYYY-MM-DD'),
[countColumn]: { [Op.gt]: 0 },
},
group: ['ref_id'],
order: [[fn('SUM', col(countColumn)), 'DESC'], ['ref_id', 'ASC']],
order: [
[fn('SUM', col(countColumn)), 'DESC'],
['ref_id', 'ASC'],
],
raw: true,
})) as any[];
const crons = rows.length > 0 ? await CrontabModel.findAll({
attributes: ['id', 'name', 'command'],
where: { id: { [Op.in]: rows.map((row) => Number(row.ref_id)) } },
raw: true,
}) : [];
const crons =
rows.length > 0
? await CrontabModel.findAll({
attributes: ['id', 'name', 'command'],
where: {
id: { [Op.in]: rows.map((row) => Number(row.ref_id)) },
},
raw: true,
})
: [];
const cronMap = new Map(crons.map((cron) => [cron.id, cron]));
res.send({
code: 200,
@@ -192,7 +300,9 @@ export default (app: Router) => {
id,
name: cron?.name || cron?.command || tf('任务#%s', id),
command: cron?.command || '',
[isSuccess ? 'successCount' : 'failCount']: Number(row.result_count),
[isSuccess ? 'successCount' : 'failCount']: Number(
row.result_count,
),
deleted: !cron,
};
}),
@@ -212,9 +322,10 @@ export default (app: Router) => {
const days =
requestedDays === undefined
? 7
: typeof requestedDays === 'string' && /^[1-9]\d{0,2}$/.test(requestedDays)
? Number(requestedDays)
: NaN;
: typeof requestedDays === 'string' &&
/^[1-9]\d{0,2}$/.test(requestedDays)
? Number(requestedDays)
: NaN;
if (!Number.isInteger(days) || days > 365) {
return res.status(400).send({ code: 400, message: t('无效的天数') });
}
@@ -286,12 +397,14 @@ export default (app: Router) => {
raw: true,
});
const nameMap: Record<number, string> = {};
crons.forEach((c: any) => { nameMap[c.id] = c.name || c.command; });
crons.forEach((c: any) => {
nameMap[c.id] = c.name || c.command;
});
const data = rows.map((r: any, i) => ({
rank: i + 1,
name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id),
avgTime: averageElapsed(r.total_time,r.run_count,r.untimed_count),
avgTime: averageElapsed(r.total_time, r.run_count, r.untimed_count),
maxTime: Number(r.max_time),
}));
@@ -329,16 +442,20 @@ export default (app: Router) => {
raw: true,
});
const nameMap: Record<number, string> = {};
crons.forEach((c: any) => { nameMap[c.id] = c.name || c.command; });
crons.forEach((c: any) => {
nameMap[c.id] = c.name || c.command;
});
const data = rows.map((r: any, i) => ({
rank: i + 1,
name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id),
runCount: Number(r.run_count),
avgTime: averageElapsed(r.total_time,r.run_count,r.untimed_count),
avgTime: averageElapsed(r.total_time, r.run_count, r.untimed_count),
successRate:
Number(r.run_count) > 0
? ((Number(r.success_count) / Number(r.run_count)) * 100).toFixed(1)
? ((Number(r.success_count) / Number(r.run_count)) * 100).toFixed(
1,
)
: '0',
}));
@@ -353,7 +470,9 @@ export default (app: Router) => {
'/runtime',
async (req: Request, res: Response, next: NextFunction) => {
try {
const queued = await new TriggerHistory(CrontabModel.sequelize!).queueCounts();
const queued = await new TriggerHistory(
CrontabModel.sequelize!,
).queueCounts();
const runningInstances = await RunningInstanceModel.findAll({
where: {
status: InstanceStatus.running,
@@ -368,9 +487,9 @@ export default (app: Router) => {
const crons =
cronIds.length > 0
? await CrontabModel.findAll({
where: { id: cronIds },
raw: true,
})
where: { id: cronIds },
raw: true,
})
: [];
const cronMap = new Map(crons.map((c: any) => [c.id, c]));
@@ -405,7 +524,9 @@ export default (app: Router) => {
runningCount: running.length,
queuedCount: queued.triggers,
queuedTasks: queued.tasks,
oldestQueued: queued.triggers ? await oldestQueued(CrontabModel.sequelize!) : [],
oldestQueued: queued.triggers
? await oldestQueued(CrontabModel.sequelize!)
: [],
running,
idleTasks: idleTasks.map((c: any) => ({
id: c.id,
@@ -427,27 +548,49 @@ export default (app: Router) => {
async (req: Request, res: Response, next: NextFunction) => {
try {
const today = dayjs().format('YYYY-MM-DD');
const [crons, stats] = (await Promise.all([
const [crons, stats] = await Promise.all([
CrontabModel.findAll({ where: { isDisabled: 0 }, raw: true }),
CrontabStatModel.findAll({ where: { date: today }, raw: true }),
]));
]);
const statMap: Record<number, any> = {};
stats.forEach((s: any) => { statMap[s.ref_id] = s; });
stats.forEach((s: any) => {
statMap[s.ref_id] = s;
});
const labelMap: Record<string, { count: number; runs: number; success: number; untimed: number; totalTime: number }> = {};
const labelMap: Record<
string,
{
count: number;
runs: number;
success: number;
untimed: number;
totalTime: number;
}
> = {};
crons.forEach((c) => {
let rawLabels = c.labels;
if (typeof rawLabels === 'string') rawLabels = JSON.parse(rawLabels);
const labels: string[] = Array.isArray(rawLabels)
? [...new Set((rawLabels as string[]).filter((l: string) => !isEmpty(l)))]
? [
...new Set(
(rawLabels as string[]).filter((l: string) => !isEmpty(l)),
),
]
: [];
if (labels.length === 0) {
labels.push(t('未分类'));
}
const st = statMap[c.id!];
labels.forEach((label: string) => {
if (!labelMap[label]) labelMap[label] = { count: 0, runs: 0, success: 0, untimed: 0, totalTime: 0 };
if (!labelMap[label])
labelMap[label] = {
count: 0,
runs: 0,
success: 0,
untimed: 0,
totalTime: 0,
};
labelMap[label].count += 1;
if (st) {
labelMap[label].runs += Number(st.run_count) || 0;
@@ -463,8 +606,9 @@ export default (app: Router) => {
label,
count: v.count,
todayRuns: v.runs,
successRate: v.runs > 0 ? ((v.success / v.runs) * 100).toFixed(1) : '0',
avgTime: averageElapsed(v.totalTime,v.runs,v.untimed),
successRate:
v.runs > 0 ? ((v.success / v.runs) * 100).toFixed(1) : '0',
avgTime: averageElapsed(v.totalTime, v.runs, v.untimed),
}))
.sort((a, b) => b.todayRuns - a.todayRuns);
+14 -6
View File
@@ -259,7 +259,10 @@ export default (app: Router) => {
async (req: Request, res: Response, next: NextFunction) => {
try {
const envService = Container.get(EnvService);
const data = await envService.removeLabels(req.body.ids, req.body.labels);
const data = await envService.removeLabels(
req.body.ids,
req.body.labels,
);
return res.send({ code: 200, data });
} catch (e) {
return next(e);
@@ -285,10 +288,13 @@ export default (app: Router) => {
: [parseContent];
if (
data.length > 0 &&
data.every((x) =>
x && typeof x.name === 'string' &&
/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(x.name) &&
typeof x.value === 'string' && x.value.length > 0,
data.every(
(x) =>
x &&
typeof x.name === 'string' &&
/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(x.name) &&
typeof x.value === 'string' &&
x.value.length > 0,
)
) {
const result = await envService.create(
@@ -303,7 +309,9 @@ export default (app: Router) => {
} else {
return res.send({
code: 400,
message: t('每条数据 name 或者 value 字段不能为空,参考导出文件格式'),
message: t(
'每条数据 name 或者 value 字段不能为空,参考导出文件格式',
),
});
}
} catch (e) {
+25 -19
View File
@@ -1,15 +1,14 @@
import { directoryCheckHandler, directoryPageHandler } from '../shared/directoryPageRoute';
import {
directoryCheckHandler,
directoryPageHandler,
} from '../shared/directoryPageRoute';
import { celebrate, Joi } from 'celebrate';
import { NextFunction, Request, Response, Router } from 'express';
import { Container } from 'typedi';
import { Logger } from 'winston';
import config from '../config';
import { t } from '../shared/i18n';
import {
readDirs,
removeAnsi,
rmPath,
} from '../config/util';
import { readDirs, removeAnsi, rmPath } from '../config/util';
import LogService from '../services/log';
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
import { MAX_LOG_CHUNK_BYTES, readLogChunk } from '../shared/logReader';
@@ -19,8 +18,14 @@ const blacklist = ['.tmp'];
export default (app: Router) => {
app.use('/logs', route);
route.get('/entries', ...directoryPageHandler(() => config.logPath, blacklist, true));
route.post('/entries/check', ...directoryCheckHandler(() => config.logPath, blacklist));
route.get(
'/entries',
...directoryPageHandler(() => config.logPath, blacklist, true),
);
route.post(
'/entries/check',
...directoryCheckHandler(() => config.logPath, blacklist),
);
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
const logger: Logger = Container.get('logger');
@@ -43,7 +48,9 @@ export default (app: Router) => {
path: Joi.string().allow('').optional(),
file: Joi.string().required(),
follow: Joi.boolean().optional(),
cursor: Joi.string().pattern(/^\d{1,16}\.[a-f0-9]{64}$/).optional(),
cursor: Joi.string()
.pattern(/^\d{1,16}\.[a-f0-9]{64}$/)
.optional(),
offset: Joi.number().integer().min(0).optional(),
limit: Joi.number()
.integer()
@@ -67,7 +74,9 @@ export default (app: Router) => {
message: t('暂无权限'),
});
}
const logPath = `${req.query.path as string}/${req.query.file as string}`;
const logPath = `${req.query.path as string}/${
req.query.file as string
}`;
const runningInstance = await RunningInstanceModel.findOne({
where: { log_path: logPath, status: InstanceStatus.running },
});
@@ -96,15 +105,12 @@ export default (app: Router) => {
},
);
route.get(
'/:file',
(req: Request, res: Response) => {
return res.send({
code: 410,
message: t('接口已下线,请使用 /logs/detail 接口'),
});
},
);
route.get('/:file', (req: Request, res: Response) => {
return res.send({
code: 410,
message: t('接口已下线,请使用 /logs/detail 接口'),
});
});
route.delete(
'/',
+10 -4
View File
@@ -56,7 +56,8 @@ function writablePath(targetPath: string, req?: Request): string {
if (
/(?:^|\/)open\/scripts(?:\/|\?|$)/.test(req?.originalUrl || '') &&
!resolveFileAccess(config.scriptPath, [normalized])
) return '';
)
return '';
if (!isPathAllowed(normalized)) return '';
for (const writableRoot of config.writePathList) {
const root = resolve(writableRoot) + sep;
@@ -554,7 +555,8 @@ export default (app: Router) => {
}
const { name, ext } = parse(filename);
const filePath = writablePath(
join(config.scriptPath, path, `${name}.swap${ext}`), req,
join(config.scriptPath, path, `${name}.swap${ext}`),
req,
);
if (!filePath) {
return res.send({ code: 403, message: t('暂无权限') });
@@ -587,7 +589,8 @@ export default (app: Router) => {
}
const { name, ext } = parse(filename);
const filePath = writablePath(
join(config.scriptPath, path, `${name}.swap${ext}`), req,
join(config.scriptPath, path, `${name}.swap${ext}`),
req,
);
if (!filePath) {
return res.send({ code: 403, message: t('暂无权限') });
@@ -635,7 +638,10 @@ export default (app: Router) => {
if (!path) {
path = '';
}
const filePath = writablePath(join(config.scriptPath, path, filename), req);
const filePath = writablePath(
join(config.scriptPath, path, filename),
req,
);
const newPath = writablePath(
join(config.scriptPath, path, newFilename),
req,
+1 -1
View File
@@ -3,7 +3,7 @@ import { Container } from 'typedi';
import { Logger } from 'winston';
import SubscriptionService from '../services/subscription';
import { celebrate, Joi } from 'celebrate';
import { isValidCronSchedule } from '../shared/cronSchedule';
import { isValidCronSchedule } from '../cron/scheduling/cronSchedule';
const route = Router();
export default (app: Router) => {
+9 -3
View File
@@ -10,7 +10,7 @@ import UserService from '../services/user';
import { t } from '../shared/i18n';
import { isDefaultAuthInfo } from '../shared/auth';
import { getUniqPath, handleLogPath, parseVersion } from '../config/util';
import { findCronId } from '../shared/cronCommand';
import { findCronId } from '../cron/execution/cronCommand';
import dayjs from 'dayjs';
import multer from 'multer';
import { logStreamManager } from '../shared/logStreamManager';
@@ -63,8 +63,14 @@ export default (app: Router) => {
try {
const systemService = Container.get(SystemService);
const data = await systemService.getSystemConfig();
res.send({ code: 200, data: { ...data, effectiveCronConcurrency: systemService.cronConcurrency,
availableCpus: containerResources().cpus } });
res.send({
code: 200,
data: {
...data,
effectiveCronConcurrency: systemService.cronConcurrency,
availableCpus: containerResources().cpus,
},
});
} catch (e) {
return next(e);
}