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
+281
-859
File diff suppressed because it is too large.
Load diff
@@ -21,7 +21,7 @@ import {
|
||||
|
||||
@Service()
|
||||
export default class EnvService {
|
||||
constructor(@Inject('logger') private logger: winston.Logger) { }
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
public async create(payloads: Env[]): Promise<Env[]> {
|
||||
payloads.forEach((payload) => assertAllowedTaskEnvName(payload.name));
|
||||
@@ -277,9 +277,9 @@ export default class EnvService {
|
||||
.replace(/'/g, "'\\''")
|
||||
.trim();
|
||||
env_string += `export ${key}='${value}'\n`;
|
||||
js_env_string += `process.env[${JSON.stringify(key)}]=${JSON.stringify(
|
||||
group.map((x) => x.value).join('&'),
|
||||
)};\n`;
|
||||
js_env_string += `process.env[${JSON.stringify(
|
||||
key,
|
||||
)}]=${JSON.stringify(group.map((x) => x.value).join('&'))};\n`;
|
||||
// Serialize data instead of constructing an escaped Python literal.
|
||||
py_env_string += `os.environ['${key}']=json.loads(${JSON.stringify(
|
||||
JSON.stringify(group.map((x) => x.value).join('&')),
|
||||
|
||||
+20
-6
@@ -27,20 +27,29 @@ export class GrpcServerService {
|
||||
async initialize() {
|
||||
try {
|
||||
this.server.addService(HealthService, { check });
|
||||
this.server.addService(CronService, { addCron: registeredAdd, delCron: registeredDelete, setConcurrency });
|
||||
this.server.addService(CronService, {
|
||||
addCron: registeredAdd,
|
||||
delCron: registeredDelete,
|
||||
setConcurrency,
|
||||
});
|
||||
this.server.addService(ApiService, Api);
|
||||
|
||||
const tlsConfig = await initGrpcCerts();
|
||||
const credentials = ServerCredentials.createSsl(
|
||||
Buffer.from(tlsConfig.caCert),
|
||||
[{ cert_chain: Buffer.from(tlsConfig.serverCert), private_key: Buffer.from(tlsConfig.serverKey) }],
|
||||
[
|
||||
{
|
||||
cert_chain: Buffer.from(tlsConfig.serverCert),
|
||||
private_key: Buffer.from(tlsConfig.serverKey),
|
||||
},
|
||||
],
|
||||
true,
|
||||
);
|
||||
|
||||
const grpcPort = config.grpcPort;
|
||||
const hostsToTry = [
|
||||
config.bindHostGrpc,
|
||||
...(config.bindHostGrpc === '::' ? ['0.0.0.0'] : [])
|
||||
...(config.bindHostGrpc === '::' ? ['0.0.0.0'] : []),
|
||||
];
|
||||
const bindAsync = promisify(this.server.bindAsync).bind(this.server);
|
||||
|
||||
@@ -50,15 +59,20 @@ export class GrpcServerService {
|
||||
try {
|
||||
const address = this.formatGrpcAddress(host, grpcPort);
|
||||
const boundPort = await bindAsync(address, credentials);
|
||||
Logger.debug(`[boot] gRPC service started successfully on ${address}`);
|
||||
Logger.debug(
|
||||
`[boot] gRPC service started successfully on ${address}`,
|
||||
);
|
||||
metricsService.record('grpc_service_start', 1, {
|
||||
port: grpcPort.toString(),
|
||||
host
|
||||
host,
|
||||
});
|
||||
return boundPort;
|
||||
} catch (err) {
|
||||
lastError = err as Error;
|
||||
Logger.warn(`Failed to bind gRPC on ${host}:${grpcPort}, trying next...`, err);
|
||||
Logger.warn(
|
||||
`Failed to bind gRPC on ${host}:${grpcPort}, trying next...`,
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+24
-12
@@ -12,7 +12,7 @@ export class HttpServerService {
|
||||
async initialize(expressApp: express.Application, port: number) {
|
||||
const hostsToTry = [
|
||||
config.bindHost,
|
||||
...(config.bindHost === '::' ? ['0.0.0.0'] : [])
|
||||
...(config.bindHost === '::' ? ['0.0.0.0'] : []),
|
||||
];
|
||||
|
||||
let lastError: Error | null = null;
|
||||
@@ -20,16 +20,21 @@ export class HttpServerService {
|
||||
for (const host of hostsToTry) {
|
||||
try {
|
||||
const server = await this.tryListen(expressApp, port, host);
|
||||
Logger.debug(`[boot] HTTP service started successfully on ${host}:${port}`);
|
||||
Logger.debug(
|
||||
`[boot] HTTP service started successfully on ${host}:${port}`,
|
||||
);
|
||||
metricsService.record('http_service_start', 1, {
|
||||
port: port.toString(),
|
||||
host
|
||||
host,
|
||||
});
|
||||
this.server = server;
|
||||
return server;
|
||||
} catch (err) {
|
||||
lastError = err as Error;
|
||||
Logger.warn(`Failed to bind HTTP on ${host}:${port}, trying next...`, err);
|
||||
Logger.warn(
|
||||
`Failed to bind HTTP on ${host}:${port}, trying next...`,
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,17 +42,24 @@ export class HttpServerService {
|
||||
throw lastError || new Error('Failed to start HTTP service');
|
||||
}
|
||||
|
||||
private async tryListen(expressApp: express.Application, port: number, host: string): Promise<Server> {
|
||||
private async tryListen(
|
||||
expressApp: express.Application,
|
||||
port: number,
|
||||
host: string,
|
||||
): Promise<Server> {
|
||||
return new Promise((resolve, reject) => {
|
||||
// There is one HTTP worker; accepting here avoids primary IPC handoff
|
||||
// for every connection. Restore shared listening for custom clusters.
|
||||
const server = expressApp.listen({
|
||||
port,
|
||||
host,
|
||||
exclusive: process.env.QL_HTTP_SHARED_LISTEN !== 'true',
|
||||
}, () => {
|
||||
resolve(server);
|
||||
});
|
||||
const server = expressApp.listen(
|
||||
{
|
||||
port,
|
||||
host,
|
||||
exclusive: process.env.QL_HTTP_SHARED_LISTEN !== 'true',
|
||||
},
|
||||
() => {
|
||||
resolve(server);
|
||||
},
|
||||
);
|
||||
|
||||
server.on('error', (err: Error) => {
|
||||
server.close();
|
||||
|
||||
@@ -8,6 +8,10 @@ export default class LogService {
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
public checkFilePath(filePath: string, fileName: string) {
|
||||
return resolveFileAccess(config.logPath, [filePath || '', fileName], ['.tmp']);
|
||||
return resolveFileAccess(
|
||||
config.logPath,
|
||||
[filePath || '', fileName],
|
||||
['.tmp'],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,16 @@
|
||||
import { persistNotificationAudit } from '../shared/notificationAudit';
|
||||
import crypto from 'crypto';
|
||||
import nodemailer from 'nodemailer';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { Service } from 'typedi';
|
||||
import { parseBody, parseHeaders } from '../config/util';
|
||||
import { NotificationInfo } from '../data/notify';
|
||||
import { t } from '../shared/i18n';
|
||||
import UserService from './user';
|
||||
import { readNotificationMode } from '../data/notificationSettings';
|
||||
import { httpClient } from '../config/http';
|
||||
import { ProxyAgent } from 'undici';
|
||||
|
||||
@Service()
|
||||
export default class NotificationService {
|
||||
@Inject((type) => UserService)
|
||||
private userService!: UserService;
|
||||
|
||||
private modeMap = new Map([
|
||||
['gotify', this.gotify],
|
||||
['goCqHttpBot', this.goCqHttpBot],
|
||||
@@ -59,7 +56,7 @@ export default class NotificationService {
|
||||
let type: string | undefined;
|
||||
let success = false;
|
||||
try {
|
||||
const saved = await this.userService.getNotificationMode();
|
||||
const saved = await readNotificationMode();
|
||||
type = notificationInfo?.type || saved.type;
|
||||
if (type) {
|
||||
this.title = title;
|
||||
|
||||
+71
-42
@@ -6,8 +6,8 @@ import { Service } from 'typedi';
|
||||
import config from '../config';
|
||||
import { CrontabStatModel } from '../data/cronStats';
|
||||
import { sequelize } from '../data';
|
||||
import { TriggerHistory } from '../shared/triggerHistory';
|
||||
import { prunedExitMigrationId } from '../shared/schemaMigrations';
|
||||
import { TriggerHistory } from '../cron/history';
|
||||
import { prunedExitMigrationId } from '../data/schemaMigrations';
|
||||
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
||||
import { AuthDataType, SystemModel } from '../data/system';
|
||||
import {
|
||||
@@ -27,8 +27,11 @@ function runningInstanceWhere(cutoffMs: number) {
|
||||
const cutoff = cutoffMs / 1000;
|
||||
return {
|
||||
status: { [Op.ne]: InstanceStatus.running },
|
||||
id: { [Op.notIn]: literal(`(SELECT instance_id FROM CronTriggers WHERE instance_id IS NOT NULL
|
||||
AND (exit_pending=1 OR state IN ('queued','running') OR finished_at IS NULL OR observed_at >= ${cutoffMs} OR finished_at >= ${cutoffMs}))`) },
|
||||
id: {
|
||||
[Op.notIn]:
|
||||
literal(`(SELECT instance_id FROM CronTriggers WHERE instance_id IS NOT NULL
|
||||
AND (exit_pending=1 OR state IN ('queued','running') OR finished_at IS NULL OR observed_at >= ${cutoffMs} OR finished_at >= ${cutoffMs}))`),
|
||||
},
|
||||
[Op.or]: [
|
||||
{ finished_at: { [Op.lt]: cutoff } },
|
||||
{
|
||||
@@ -42,8 +45,13 @@ function runningInstanceWhere(cutoffMs: number) {
|
||||
function retentionCutoffs(policy: RetentionPolicy) {
|
||||
const now = dayjs();
|
||||
return {
|
||||
history: now.subtract(policy.runningInstanceRetentionDays, 'day').startOf('second').valueOf(),
|
||||
firstDay: now.subtract(policy.cronStatRetentionDays, 'day').format('YYYY-MM-DD'),
|
||||
history: now
|
||||
.subtract(policy.runningInstanceRetentionDays, 'day')
|
||||
.startOf('second')
|
||||
.valueOf(),
|
||||
firstDay: now
|
||||
.subtract(policy.cronStatRetentionDays, 'day')
|
||||
.format('YYYY-MM-DD'),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -69,34 +77,38 @@ export default class RetentionService {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
public async preview(request: StorageCleanupRequest, cutoffs = retentionCutoffs(normalizeRetentionPolicy(request))) {
|
||||
public async preview(
|
||||
request: StorageCleanupRequest,
|
||||
cutoffs = retentionCutoffs(normalizeRetentionPolicy(request)),
|
||||
) {
|
||||
const policy = normalizeRetentionPolicy(request);
|
||||
const dependenceCacheTypes = (request.dependenceCacheTypes || []).filter(
|
||||
isDependenceCacheType,
|
||||
);
|
||||
const [runningInstances, cronStats, dependenceCaches, triggers] = await Promise.all([
|
||||
policy.runningInstanceRetentionDays > 0
|
||||
? RunningInstanceModel.count({
|
||||
where: runningInstanceWhere(cutoffs.history),
|
||||
})
|
||||
: 0,
|
||||
policy.cronStatRetentionDays > 0
|
||||
? CrontabStatModel.count({
|
||||
where: { date: { [Op.lt]: cutoffs.firstDay } },
|
||||
})
|
||||
: 0,
|
||||
Promise.all(
|
||||
dependenceCacheTypes.map(async (type) => ({
|
||||
type,
|
||||
bytes: await getDirectorySize(
|
||||
path.join(config.dependenceCachePath, type),
|
||||
),
|
||||
})),
|
||||
),
|
||||
policy.runningInstanceRetentionDays > 0
|
||||
? new TriggerHistory(sequelize).countExpired(cutoffs.history)
|
||||
: 0,
|
||||
]);
|
||||
const [runningInstances, cronStats, dependenceCaches, triggers] =
|
||||
await Promise.all([
|
||||
policy.runningInstanceRetentionDays > 0
|
||||
? RunningInstanceModel.count({
|
||||
where: runningInstanceWhere(cutoffs.history),
|
||||
})
|
||||
: 0,
|
||||
policy.cronStatRetentionDays > 0
|
||||
? CrontabStatModel.count({
|
||||
where: { date: { [Op.lt]: cutoffs.firstDay } },
|
||||
})
|
||||
: 0,
|
||||
Promise.all(
|
||||
dependenceCacheTypes.map(async (type) => ({
|
||||
type,
|
||||
bytes: await getDirectorySize(
|
||||
path.join(config.dependenceCachePath, type),
|
||||
),
|
||||
})),
|
||||
),
|
||||
policy.runningInstanceRetentionDays > 0
|
||||
? new TriggerHistory(sequelize).countExpired(cutoffs.history)
|
||||
: 0,
|
||||
]);
|
||||
|
||||
return {
|
||||
policy,
|
||||
@@ -117,7 +129,10 @@ export default class RetentionService {
|
||||
const preview = await this.preview(request, cutoffs);
|
||||
const deleted = await sequelize.transaction(async (transaction) => {
|
||||
const history = new TriggerHistory(sequelize);
|
||||
if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) {
|
||||
if (
|
||||
preview.policy.runningInstanceRetentionDays ||
|
||||
preview.policy.cronStatRetentionDays
|
||||
) {
|
||||
await history.replayPublishedExits(transaction);
|
||||
}
|
||||
const runningInstances =
|
||||
@@ -130,27 +145,41 @@ export default class RetentionService {
|
||||
let cronStats = 0;
|
||||
if (preview.policy.cronStatRetentionDays > 0) {
|
||||
const firstDay = cutoffs.firstDay;
|
||||
cronStats = await CrontabStatModel.destroy({ where: { date: { [Op.lt]: firstDay } }, transaction });
|
||||
await sequelize.query(`INSERT INTO CronStatRetention(id,first_day) VALUES (1,$firstDay)
|
||||
cronStats = await CrontabStatModel.destroy({
|
||||
where: { date: { [Op.lt]: firstDay } },
|
||||
transaction,
|
||||
});
|
||||
await sequelize.query(
|
||||
`INSERT INTO CronStatRetention(id,first_day) VALUES (1,$firstDay)
|
||||
ON CONFLICT(id) DO UPDATE SET first_day=MAX(first_day,excluded.first_day)`,
|
||||
{ bind: { firstDay }, transaction });
|
||||
await sequelize.query(`DELETE FROM CronPrunedUnknownRuns WHERE last_possible_day <
|
||||
(SELECT first_day FROM CronStatRetention WHERE id=1)`, { transaction });
|
||||
{ bind: { firstDay }, transaction },
|
||||
);
|
||||
await sequelize.query(
|
||||
`DELETE FROM CronPrunedUnknownRuns WHERE last_possible_day <
|
||||
(SELECT first_day FROM CronStatRetention WHERE id=1)`,
|
||||
{ transaction },
|
||||
);
|
||||
}
|
||||
const triggers = preview.policy.runningInstanceRetentionDays > 0
|
||||
? await history.deleteExpired(cutoffs.history, transaction)
|
||||
: 0;
|
||||
if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) {
|
||||
const triggers =
|
||||
preview.policy.runningInstanceRetentionDays > 0
|
||||
? await history.deleteExpired(cutoffs.history, transaction)
|
||||
: 0;
|
||||
if (
|
||||
preview.policy.runningInstanceRetentionDays ||
|
||||
preview.policy.cronStatRetentionDays
|
||||
) {
|
||||
// An unbound receipt's day can be wrong. A later bound receipt still
|
||||
// needs the execution-to-task link even after both visible histories expire.
|
||||
// A writer can also win the lock before an interrupted upgrade retries.
|
||||
// Keep its bound bookings until the proof-copy transaction has committed.
|
||||
await sequelize.query(`DELETE FROM CronLegacyExitBookings WHERE day <
|
||||
await sequelize.query(
|
||||
`DELETE FROM CronLegacyExitBookings WHERE day <
|
||||
(SELECT first_day FROM CronStatRetention WHERE id=1)
|
||||
AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=CronLegacyExitBookings.trigger_id)
|
||||
AND ((bound=1 AND EXISTS (SELECT 1 FROM SchemaMigrations WHERE id=$proofMigration))
|
||||
OR (bound=0 AND NOT EXISTS (SELECT 1 FROM Crontabs WHERE id=CronLegacyExitBookings.cron_id)))`,
|
||||
{ bind: { proofMigration: prunedExitMigrationId }, transaction });
|
||||
{ bind: { proofMigration: prunedExitMigrationId }, transaction },
|
||||
);
|
||||
}
|
||||
return { runningInstances, cronStats, triggers };
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { t } from '../shared/i18n';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import { createCronJob, CronJob } from '../shared/cronScheduler';
|
||||
import { createCronJob, CronJob } from '../cron/scheduling/cronScheduler';
|
||||
import { ChildProcessWithoutNullStreams } from 'child_process';
|
||||
import {
|
||||
ToadScheduler,
|
||||
|
||||
@@ -8,7 +8,7 @@ import ScheduleService, { TaskCallbacks } from './schedule';
|
||||
import config from '../config';
|
||||
import { TASK_COMMAND } from '../config/const';
|
||||
import { getFileContentByName, getPid, killTask, rmPath } from '../config/util';
|
||||
import taskLimit from '../shared/pLimit';
|
||||
import taskLimit from '../cron/execution/cronLimit';
|
||||
|
||||
@Service()
|
||||
export default class ScriptService {
|
||||
|
||||
@@ -7,7 +7,7 @@ import { SockMessage } from '../data/sock';
|
||||
export default class SockService {
|
||||
private clients: Connection[] = [];
|
||||
|
||||
constructor(@Inject('logger') private logger: winston.Logger) { }
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
public getClients() {
|
||||
return this.clients;
|
||||
|
||||
@@ -149,7 +149,10 @@ export default class SubscriptionService {
|
||||
let beforeStr = '';
|
||||
try {
|
||||
if (doc.sub_before) {
|
||||
await logStreamManager.write(absolutePath, `\n## ${t('执行before命令...')}\n\n`);
|
||||
await logStreamManager.write(
|
||||
absolutePath,
|
||||
`\n## ${t('执行before命令...')}\n\n`,
|
||||
);
|
||||
beforeStr = await promiseExec(doc.sub_before);
|
||||
}
|
||||
} catch (error: any) {
|
||||
@@ -186,7 +189,8 @@ export default class SubscriptionService {
|
||||
}
|
||||
} catch (error: any) {
|
||||
afterStr =
|
||||
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
||||
(error.stderr && error.stderr.toString()) ||
|
||||
JSON.stringify(error);
|
||||
}
|
||||
if (afterStr) {
|
||||
await logStreamManager.write(absolutePath, `${afterStr}\n`);
|
||||
@@ -321,7 +325,9 @@ export default class SubscriptionService {
|
||||
// A URL accepted by one engine can produce an invalid name in another.
|
||||
// Validate each candidate independently, retaining the safe candidate.
|
||||
if (!Object.values(names).every(isSubscriptionStorageName)) continue;
|
||||
const resolve = deleting ? resolveSubscriptionStoragePath : path.resolve;
|
||||
const resolve = deleting
|
||||
? resolveSubscriptionStoragePath
|
||||
: path.resolve;
|
||||
const scriptPath = resolve(config.scriptPath, names.script);
|
||||
if (scriptPath) targets.push(scriptPath);
|
||||
if (names.repo) {
|
||||
@@ -329,7 +335,10 @@ export default class SubscriptionService {
|
||||
if (repoPath) targets.push(repoPath);
|
||||
}
|
||||
if (names.raw) {
|
||||
const rawPath = resolve(path.join(config.dataPath, 'raw'), names.raw);
|
||||
const rawPath = resolve(
|
||||
path.join(config.dataPath, 'raw'),
|
||||
names.raw,
|
||||
);
|
||||
if (rawPath) targets.push(rawPath);
|
||||
}
|
||||
}
|
||||
@@ -364,10 +373,11 @@ export default class SubscriptionService {
|
||||
for (const storagePath of new Set(storagePaths)) {
|
||||
// rm is recursive: an ancestor must also be retained if a surviving
|
||||
// subscription uses a nested branch, and vice versa.
|
||||
const shared = retainedPaths.some((retained) =>
|
||||
retained === storagePath ||
|
||||
retained.startsWith(`${storagePath}${path.sep}`) ||
|
||||
storagePath.startsWith(`${retained}${path.sep}`),
|
||||
const shared = retainedPaths.some(
|
||||
(retained) =>
|
||||
retained === storagePath ||
|
||||
retained.startsWith(`${storagePath}${path.sep}`) ||
|
||||
storagePath.startsWith(`${retained}${path.sep}`),
|
||||
);
|
||||
if (!shared) await rmPath(storagePath);
|
||||
}
|
||||
|
||||
@@ -36,9 +36,9 @@ import {
|
||||
NotifyStatus,
|
||||
NotifyLogInfo,
|
||||
} from '../data/system';
|
||||
import taskLimit from '../shared/pLimit';
|
||||
import taskLimit from '../cron/execution/cronLimit';
|
||||
import cronClient from '../schedule/client';
|
||||
import { withSchedulerMutation } from '../shared/schedulerMutationLock';
|
||||
import { withSchedulerMutation } from '../cron/scheduling/schedulerMutationLock';
|
||||
import NotificationService from './notify';
|
||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||
import SockService from './sock';
|
||||
|
||||
Reference in new issue
Block a user