mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 09:45:36 +08:00
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:
1 parent
77ece406ac
commit
c5458596c8
346 files changed
+32133
-11556
No files matched your search
+208
-83
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user